Passing Function Arguments in C : Call By Reference

When we call a function by reference then the actual value of supplied argument is modified within the function. In this method the address of an argument is copied into the formal parameter, and inside the function the address is used to access the actual argument used in the call. This means that changes made to the parameter affect  the argument.

In the call by reference we need pass a pointer to an argument, instead of the argument itself. Since the address of the argument is passed to the function, code within the function can change the value of the argument outside the function.

Pointers are passed to the function just like any other value. To do this we need to declare the formal parameter as pointer types. For example :
data_type function_name(data_type *param1, data_type *param2)
Example :
int Myfunc(int *p1, int *p2)
And also we have to use the & ( ampersand ) symbol with arguments at function call.
Myfunc(&a, &b);
The & represents the reference (or address) of the variable, and it is also known as 'address of' operator.

Now lets take a look at below example code.
void swap(int *a, int *b) {
  int temp;

  temp = *a;  // save the value at address a
  *a = *b;    // put b into a
  *b = temp;  // put a into b
}
At above code, the function swap() exchange the values of the two variables pointed to by a and b, because their address are passed (not their values). Thus within the function, the contents of the variables can be accessed using standard pointer operations, and the contents of the variables used to call the function are swapped. Now remember that any function that uses pointer parameters must be called with the addresses of the arguments.

Example Code :
#include <stdio.h>

void swap(int *, int *);

int main() {
  int x, y;

  x = 20;
  y = 40;

  printf("x : %d, y : %d\n", x, y);

  swap(&x, &y);

  printf("After swapping...\n");
  printf("x : %d, y : %d\n", x, y);
  return 0;
}

void swap(int *a, int *b) {
  int temp;

  temp = *a;  // save the value at address a
  *a = *b;    // put b into a
  *b = temp;  // put a into b
}
Output :

x : 20, y : 40
After swapping...
x : 40, y : 20

At the above example The variable x is assigned to the value 20 and y is assigned to the value 40. Then swap() is called with the address of x and y with the address of ( & ) operator. Therefore, the addresses of x and y are passed into the function swap(). After swap() returns, the values of x and y will be exchanged.

Next Topic :