C语言 函数参数引用传递
通过引用调用向函数传递参数的方法将参数的地址复制到参数中,在函数内部,地址用于访问调用中使用的实际参数,这意味着对参数所做的更改会影响传递的参数。
要通过引用传递一个值,参数指针被传递给函数,就像传递任何其他值一样,因此,您需要将函数参数声明为指针类型,如下面的函数swap()所示,该函数通过其参数交换指向的两个整数变量的值。
/* function definition to swap the values */
void swap(int *x, int *y) {
int temp;
temp=*x; /* save the value at address x */
*x=*y; /* put y into x */
*y=temp; /* put temp into y */
return;
}
现在让我们通过引用传递值来调用函数swap(),如下面的示例-所示
#include <stdio.h>
/* function declaration */
void swap(int *x, int *y);
int main () {
/* local variable definition */
int a=100;
int b=200;
printf("Before swap, value of a : %d\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values.
* &a indicates pointer to a ie. address of variable a and
* &b indicates pointer to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d\n", a );
printf("After swap, value of b : %d\n", b );
return 0;
}
让我们将上述代码放在一个C文件中,编译并执行它,以生成以下结果:
Before swap, value of a :100
Before swap, value of b :200
After swap, value of a :200
After swap, value of b :100
它表明更改也反映在函数外部,这与值传递不同,在值传递中更改不会反映在函数外部。