一、值传递
void exchange(int x, int y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
printf("x = %d y = %d", x, y);
}
main()
{
int a = 1;
int b = 2;
exchange(a, b);
}
输出结果:x = 1 y = 2
exchange(a, b)
函数的实际执行过程如下:
exchange(a, b)
{
int x = a;
int y = b;
int tmp;
tmp = x;
x = y;
y = tmp;
printf("x = %d y = %d", x, y);
}
可见上述的操作并没有改变a和b变量本身的值。
二、地址传递
void exchange(int *x, int *y)
{
int tmp;
tmp = *x;
*x = *y;
*y = tmp;
printf("x = %d y = %d", *x, *y);
}
main()
{
int a = 1;
int b = 2;
exchange(&a, &b);
}
输出结果:x = 2 y = 1
exchange(a, b)
函数的实际执行过程如下:
exchange(&a, &b)
{
int *x = &a;
int *y = &b;
int tmp;
tmp = *x;
*x = *y;
*y = tmp;// "*"是在对y指向的内存空间进行操作
printf("x = %d y = %d", x, y);
}
函数里的操作是对a和b变量本身进行操作。
三、引用传递
void exchange(int &x, int &y)
{
int tmp;
tmp = x;
x = y;
y = tmp;
printf("x = %d y = %d", x, y);
}
main()
{
int a = 1;
int b = 2;
exchange(a, b);
}
输出结果:x = 2 y = 1
exchange(a, b)
函数的实际执行过程如下:
exchange(a, b)
{
int &x = a; //声明一个引用并初始化
int &y = b;
int tmp;
tmp = x;
x = y;
y = tmp;// "*"是在对y指向的内存空间进行操作
printf("x = %d y = %d", x, y);
}
exchange(a, b)
这里a和b分别直接替换了x和y。
总结:
从值传递、地址传递和引用传递的实际执行过程来看,地址传递和引用传递本质上是值传递。函数参数的传递,传递的是变量的值,而不是变量本身。
网友评论