6.2 值传递的特性
上节介绍的将实参复制给形参就是一种值传递,在函数体中对形参进行的任何操作不影响实参。
代码验证:
#include <iostream>
using namespace std;
void swap(int num1, int num2)
{
cout << "交换前:" << endl;
cout << "num1=" << num1 << endl;;
cout << "num2=" << num2 << endl;;
int temp = num1;
num1 = num2;
num2 = temp;
cout << "交换后:" << endl;
cout << "num1=" << num1 << endl;
cout << "num2=" << num2 << endl;
}
int main()
{
int a = 10;
int b = 20;
swap(a, b);
cout << "================" << endl;
cout << a << '\t' << b << endl;
system("pause");
return 0;
}
运行结果:
可以看到,虽然在函数中对两个数进行了交换,但实际上a和b的值并没有改变。