What is call function by reference in C

Call function by reference means calling a function by passing the addresses of all actual parameters instead of their value. Before getting started we recommend you to see our previous guide to call function by value in C then come to this guide. If you don’t know about the use of pointer then have a look at this guide to pointer in C. This will help you to understand all of our program in this article.

Now, lets know about what are actual arguments and formal arguments or parameters of a function.

Actual arguments/parameters : These are the parameters that needs at the time of calling a function.

Formal arguments/parameters : The parameters that appears in the function declaration are known as formal parameters.

See bellow;

// formal and actual arguments or parameters in C

#include <stdio.h>
int print_sum(int a, int b){    // a and b are formal parameters
     int total = a + b;
     return total;
}

int main(){
    int x = 25;
    int y = 45;
    int sum = print_sum(x, y);    // x and y are actual parameters
    printf("Sum is = %d\n", sum);
    return 0;
}

Now come to the point.

In case of call function by reference, the operation which is performed on formal parameters, affects the value of actual parameters. Because we know that all the operations performed on the value stored in the address of actual parameters.

See the following example if it sounds confusing.

// C program to call function by reference

#include <stdio.h>

void increment(int *a){
  *a = *a + 1;
}

int main(){
  int num = 10;
  increment(&num);   // &num means the address of variable num
  printf("Value of number is = %d", num);
  return 0;
}

Output of call function by reference program

Now lets see an example program of using call function by reference method.

Swapping of two numbers using call function by reference method

// Swapping of two numbers using call function by reference method
#include <stdio.h>

void swap_number(int *x, int *y){
   int t;
   t = *x;
   *x = *y;
   *y = t;
}

int main(){
   int firstNumber = 10, secondNumber = 20;
   printf("Before swapping first number is %d and second number is %d\n", firstNumber, secondNumber);

   swap_number(&firstNumber, &secondNumber);

   printf("\nAfter swapping first number is %d and second number is %d\n", firstNumber, secondNumber);
   
   return 0;
}

See output like this

call function by reference, calling function by reference