#include <iostream>
using namespace std;
void swap(int, int);
int main()
{
int a=10;
int b=20;
swap (a, b);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
return 0;
}
void swap(int x, int y)
{
int t;
t = x;
x = y;
y = t;
}
those code above can't swap the value of a and b. but my question is , when I forgot to type the third line "void swap(int, int); " , the values of a and b swaped !! why?
It's because you have
using namespace std;
At the beginning of your source code.
This is a a bad programming practice , whose consequences you just experienced, first hand. You told the compiler that you want to invoke std::swap
, without having any clue that you actually did that.
It's ironical, because you version of swap() won't work right, but std::swap
does; so you were operating under the mistaken impression that your code was working, when it didn't.
Never use "using namespace std;" with your code. Simply forget that this part of the C++ language ever existed.
#include <iostream>
using namespace std;
int main()
{
int a = 10;
int b = 20;
cout << "a: " << a << endl;
cout << "b: " << b << endl;
system("pause");
swap(a, b);
cout << "a: " << a << endl;
cout << "b: " << b << endl;
system("pause");
return 0;
}
void swap is unnecessary
如果你把函数定义放在main之上,那么你不需要原型,否则你确实需要它,如果你没有原型,编译器会给你一个错误
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.