Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

C calling a function by value

C calling a function by value

C functions C functions

pass arguments to a function via thecall by valuemethod, which copies the actual value of the argument to the function's formal parameter. In this case, modifying the formal parameter inside the function does not affect the actual argument.

By default, the C language usescall by valuemethod to pass arguments. Generally, this means the code inside the function will not change the actual arguments used to call the function. The function swap() is defined as follows:



/* Function definition */

void swap(int x, int y)

{

   int temp;



   temp = x; /* 保存 x 的值 */

   x = y;    /* 把 y 赋值给 x */

   y = temp; /* 把 temp 赋值给 y */

  

   return;

}

Now, let us call the function by passing actual arguments swap():

Example

#include

 

/* 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 code above is compiled and executed, it produces the following result:



交换前,a 的值: 100

交换前,b 的值: 200

交换后,a 的值: 100

交换后,b 的值: 200

The example above shows that although the values of a and b are changed inside the function, in fact the values of a and b have not changed.

C functions C functions