C Call by Value

C Functions

of passing parameters to functionsCall by valuemethod, which copies the actual values of parameters to the formal parameters of the function. In this case, modifying the formal parameters within the function does not affect the actual parameters.

By default, the C language usesCall by valuemethod to pass parameters. Generally speaking, this means that the code inside the function will not change the actual parameters used to call the function. The functionswap()The definition is as follows:

/* 函数定义 */
void swap(int x, int y)
{
   int temp;

   temp = x; /* 保存 x 的值 */
   x = y;    /* 把 y 赋值给 x */
   y = temp; /* 把 temp 赋值给 y */
  
   return;
}

Now, let's call the function by passing actual parameters.swap():

Example

#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 );
 
   /* Call the function to swap values */
   swap(a, b);
 
   printf(After swap, value of a: %d\n", a );
   printf(After swap, value of b: %d\n", b );
 
   return 0;
}

When the above code is compiled and executed, it produces the following result:

交换前,a 的值: 100
交换前,b 的值: 200
交换后,a 的值: 100
交换后,b 的值: 200

The above example shows that although the values of a and b were changed inside the function, in reality the values of a and b did not change.

C Functions

other extensions