按值传递函数参数拷贝参数的实际值到函数的形式参数的方法的调用。在这种情况下,参数在函数内变化对参数没有影响。
默认情况下,C编程语言使用调用通过值的方法来传递参数。在一般情况下,这意味着,在函数内码不能改变用来调用所述函数的参数。考虑函数swap()的定义如下。
/* function definition to swap the values */
void swap(int x, int y)
{
int temp;
temp = x; /* save the value of 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", a );
printf("Before swap, value of b : %d", b );
/* calling a function to swap the values */
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 :100 After swap, value of b :200
这表明值没有改变,虽然它们已经在函数内部改变。