C语言 函数参数值传递
2019-09-09
16
0
值调用将参数传递给函数的方法将参数的实际值复制到函数参数中,在这种情况下,对函数内部参数所做的更改对参数没有影响。
默认情况下,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\n", a );
printf("Before swap, value of b : %d\n", b );
/* calling a function to swap the values */
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 :100
After swap, value of b :200
它表明这些值没有变化,尽管它们在函数内部发生了变化。