代码一:C++默认传参为值传递,x、y为a、b的副本,函数swap结束后x、y虽成功交换,但被立即释放,并不影响a、b的值。
#include <iostream>
using namespace std;
void swap(int x, int y)
{
int z;
z = x;
x = y;
y = z;
}
int main()
{
int a = 1;
int b = 9;
cout << a << "," << b << endl;
swap(a, b);
cout << a << "," << b << endl;
system("pause");
return 0;
}
程序运行结果如下:
代码二:要交换a、b的值,可以采用引用传参,引用是变量的别名,修改引用会直接修改原变量。
#include <iostream>
using namespace std;
void swap(int &x, int &y)
{
int z;
z = x;
x = y;
y = z;
}
int main()
{
int a = 1;
int b = 9;
cout << a << "," << b << endl;
swap(a, b);
cout << a << "," << b << endl;
system("pause");
return 0;
}
程序运行结果如下: