C Call by Value and Call by Reference


There are two ways to pass value or data to function in C language: call by value and call by reference. Original value is not modified in call by value but it is modified in call by reference.


Function call by value

The call by value method of passing arguments to a function copies the actual value of an argument into the formal parameter of the function. In this case, changes made to the parameter inside the function have no effect on the argument.

Example

#include <stdio.h>
 
/* function declaration */
void swap(int x, int y);
 
int main ()
{
   /* local variable definition */
   int a = 10;
   int b = 20;
 
   printf("Before swap, value of a : %d\n", a );
   printf("Before swap, value of b : %d\n", b );
 
   /* calling a function to swap the values */
   swap(a, b);
 
   printf("After swap, value of a : %d\n", a );
   printf("After swap, value of b : %d\n", b );
 
   return 0;
}
Output
Before swap, value of a :10
Before swap, value of b :20
After swap, value of a :10
After swap, value of b :20

Function call by reference

The call by reference method of passing arguments to a function copies the address of an argument into the formal parameter. 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 passed argument.

Example

#include <stdio.h>
 
/* function declaration */
void swap(int *x, int *y);
 
int main ()
{
   /* local variable definition */
   int a = 10;
   int b = 20;
 
   printf("Before swap, value of a : %d\n", a );
   printf("Before swap, value of b : %d\n", b );
 
   /* calling a function to swap the values.
    * &a indicates pointer to a ie. address of variable a and 
    * &b indicates pointer to b ie. 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;
}
Output
Before swap, value of a :10
Before swap, value of b :20
After swap, value of a :20
After swap, value of b :10

Difference between call by value and call by reference

Call by valueCall by reference
A copy of value is passed to the functionAn address of value is passed to the function
Changes made inside the function is not reflected on other functionsChanges made inside the function is reflected outside the function also
Actual and formal arguments will be created in different memory locationActual and formal arguments will be created in same memory location

Share this article on