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>
usingnamespace 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;
}
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().
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>
usingnamespace 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");
}