目录

Call by value

将参数传递给函数的value call by value方法将参数的实际值复制到函数的形式参数中。 在这种情况下,对函数内部参数所做的更改不会对参数产生影响。

默认情况下,C编程使用call by value来传递参数。 通常,它意味着函数内的代码不能改变用于调用函数的参数。 考虑函数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

它表明值没有变化,尽管它们已在函数内部进行了更改。

↑回到顶部↑
WIKI教程 @2018