通过传递函数参数拷贝参数的地址到形式参数的引用方法的调用。内部的函数,地址是用来访问调用中使用的实际参数。这意味着,对参数的更改会影响传递的参数。
要通过引用传递的值,参数的指针被传递给函数就像其他值。所以相应的需要声明函数的参数为指针类型,如下面的函数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;
}
要查看更详细的关于C - 指针,可以查看 C - 指针篇章。
现在,让我们调用函数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", a );
printf("Before swap, value of b : %d", b );
/* calling a function to swap the values.
* &a indicates yiibaier to a ie. address of variable a and
* &b indicates yiibaier to b ie. address of variable b.
*/
swap(&a, &b);
printf("After swap, value of a : %d", a );
printf("After swap, value of b : %d", 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
这表明变化的函数影响到外部,不同于通过值调用的外部体改变不能反映函数之外。