Latest web development tutorials

C function call reference

C function C function

Reference to the calling method parameters, copy the address parameters to the formal parameters passed to the function.Inside the function, the address used to access the call actual parameters to use. This means that a modified form of the parameters affect the actual parameters.

Value passed by reference, the argument pointer is passed to the function, just like other values ​​passed to the function the same. Thus Accordingly, the following functionswap (), you need to declare the function argument as a pointer type, the function value for the parameter points to exchange two integer variables.

/* 函数定义 */
void swap(int *x, int *y)
{
   int temp;
   temp = *x;    /* 保存地址 x 的值 */
   *x = *y;      /* 把 y 赋值给 x */
   *y = temp;    /* 把 temp 赋值给 y */
  
   return;
}

For more details C pointer, visit the C - Pointer section.

Now, let us pass by reference to the calling functionswap ():

#include <stdio.h>
 
/* 函数声明 */
void swap(int *x, int *y);
 
int main ()
{
   /* 局部变量定义 */
   int a = 100;
   int b = 200;
 
   printf("交换前,a 的值: %d\n", a );
   printf("交换前,b 的值: %d\n", b );
 
   /* 调用函数来交换值
    * &a 表示指向 a 的指针,即变量 a 的地址 
    * &b 表示指向 b 的指针,即变量 b 的地址 
   */
   swap(&a, &b);
 
   printf("交换后,a 的值: %d\n", a );
   printf("交换后,b 的值: %d\n", b );
 
   return 0;
}

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

Before switching, a value: 100
Before switching, b values: 200
After an exchange, a value of: 200
Following the exchange, b values: 100

The above example shows that, with the traditional values ​​of different calls, the call reference within the function to change the values ​​of a and b, in fact, changed the function outside a and b values.

C function C function