问题描述:
在学习C++函数部分的时候写了如下代码:
#include <iostream> using namespace std; int x, y,x10,y10; void swap(int x,int y) { int a = x; x = y; y = a; } int main() { cin >> x10; cin >> y10; swap(x10, y10); cout << x10; cout << y10; }
发现输出的时候x10与y10并未交换。
改变:
#include <iostream> using namespace std; int x, y,x10,y10; void swap(int x,int y) { int a = x; x = y; y = a; cout << "test" << x; cout << "test" << y; } int main() { cin >> x10; cin >> y10; swap(x10, y10); cout << x10; cout << y10; }
test文字后确实输出了交换后的结果。why???
查询资料:
当我们做值传递的时候,函数的形参发生改变,并不会影响实参。