无需先声明函数,我可以交换变量的值
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
可以工作;所以你在错误的印象下操作,认为你的代码正在工作,而事实并非如此。
切勿在代码中使用"使用命名空间 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;
}
不需要无效掉期
如果你把函数定义放在main上面,那么你就不需要原型,否则你确实需要它,如果你没有原型,编译器应该给你一个错误。
相关文章:
- 交换N个变量
- 为什么发出空asm命令会交换变量
- 是否可以通过使用移动/交换 c++11 来延长返回的临时变量的生命周期
- 如果静态变量只为程序的整个部分存储了一个副本,为什么我不能使用静态变量交换 2 个数字?
- swap(int&, int&) 函数不起作用,当交换不使用临时变量时?
- 是否可以在C++中使用宏交换两个变量的出现?
- 尝试使用 {} 和 std::make_pair() 交换两个变量时的行为不同
- 使用C++简洁地交换变量的值
- 无需先声明函数,我可以交换变量的值
- 使用指针交换字符变量
- 比较和交换三个原子变量
- 通过 xor 运算符使用引用或指针交换两个变量的值
- 交换两个数字而不使用临时变量
- 在类之间交换变量的正确方法是什么?
- 使用 if 语句交换循环变量
- 在不使用第三个变量作为中间位置的情况下交换两个变量
- 什么是用于交换2个整数变量的C代码
- 交换变量(C++,处理器级)
- 用异或交换两个变量
- 在cpp程序之间交换变量