reference does not work, please help

I want to use reference to swap i and j in below code,however, it does not work, please help.but if i put
void swap (int &, int &)
before main(), it works.Can anyone explain to me? Thanks.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{
void swap(int &, int &);
int i=3, j=5;
swap(i,j);
cout<<i<<" "<< j<<endl;
return 0;
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}
This is because

void swap(int &, int &);

is a function prototype. When you the compiler sees the function swap() with no definition, it will not know what it is. By pre-declaring it, the compiler will know that their is such a function called swap().
Last edited on
The definition may be after the use. The compiler only needs a declaration (prototype).

Your code works fine, ¿what's the error that you are getting?
Thanks,Flurite, however, what is the difference if the swap() is put inside main(), above function does not go inside swap(), but below function does, despite it does not achieve the target.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>
using namespace std;
int main()
{
void swap(int , int );

int i=3, j=5;
swap(i,j);
cout<<i<<" "<< j<<endl;
return 0;
}
void swap(int a, int b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("pass\n");
}
ne555, thanks for you reply. I want
5 3
but actually I get
3 5

and when swap() is put inside main(), seems the void swap(int &, int &) has not been executed.
Why is that?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
using namespace std;
int main()
{
void swap(int &, int &);

int i=3, j=5;
swap(i,j);
cout<<i<<" "<< j<<endl;
system("pause");
return 0;
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
printf("pass\n");
}


Prints:

pass
5 3
I still got 3 5. but following codes give 5 3.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>
using namespace std;
int main()
{
//void swap(int &, int &);
int i=3, j=5;
swap(i,j);
cout<<i<<" "<< j<<endl;
return 0;
}
void swap(int &a, int &b)
{
int temp;
temp=a;
a=b;
b=temp;
}


function prototype declaration fails?
In your "failed" code the swap function isn't taking references.
Yes, it is not executing the swap function, and i want to know why?
it works fine, I see no error, should you rebuild?
Which platform r you using, Mine is visual studio 6.0
closed account (zb0S216C)
Maybe updating your compiler will resolve the issue. Something like VC++ '10 or MinGW 4.7.

Wazzak
Topic archived. No new replies allowed.