C Call Function by Reference

C Functions

In pass-by-reference, the formal parameter is a pointer to the address of the actual argument. When an operation is performed on the formal parameter's reference, it is equivalent to performing the operation on the actual argument itself.

Passing pointers allows multiple functions to access the object referenced by the pointer, without having to declare the object as globally accessible.

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

For more details about pointers in C, please visitC - PointersChapter.

Now, let's call the function by passing values by reference.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 function to swap values
* &a represents a pointer to a, i.e., the address of variable a
* &b represents a pointer to b, i.e., the address of variable b
   */

   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 results:

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

The above example shows that, unlike call-by-value, call-by-reference changes the values of a and b inside the function, and in fact also changes the values of a and b outside the function.

C Functions

other extensions