![](/img/trans.png)
[英]Why can't I pass global Variables as parameters in function declaration
[英]without declaration the function first, I can swap the value of the variables?
#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;
}
上面的代码不能交换a和b的值。 但我的问题是,当我忘记键入第三行“void swap(int,int);”时,a和b的值会变换!! 为什么?
这是因为你有
using namespace std;
在您的源代码的开头。
这是一个糟糕的编程习惯 ,它只是你刚刚经历的后果。 你告诉编译器你要调用std::swap
,而不知道你实际上是这么做的。
这很讽刺,因为你的swap()版本不能正常工作,但std::swap
会这样做; 因此,您错误地认为您的代码正在运行,而不是。
永远不要使用“using namespace std;” 用你的代码。 简单地忘记这部分C ++语言曾经存在过。
#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是不必要的
如果你把函数定义放在main之上,那么你不需要原型,否则你确实需要它,如果你没有原型,编译器会给你一个错误
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.