What is the difference between “Call by Value” and “Call by Reference”?

Difference between call by value and call by reference

In this article, you will learn the main difference between call by value and call by reference. We will provide an example for each to help you understand better. Every variable defined within a function has local scope. It means that the compiler cannot process it outside that function. We can access it but cannot change its status, the value it holds. To change the value of a variable, outside the function, we use call by reference.

The basic difference between call by value and call by reference is that we pass actual variables in the call by value while we pass the address of variables in the call by reference. We use a pointer variable to store the address in. We declare a pointer variable via asterisk (*) operator and then we pass the address via ampersand (&) operator. If variables are passed by value, any alteration of variables in called function will not take effect. But, when we pass the address of variables, the alteration of variables can be achieved. The following examples will help you better understand the concept.

Call by Value

The following Program explains call by value. As you see in the output that no change in the values of a variable occurs during execution. We have swapped the variable in called function but no change has occurred. As you see in the output, the values of both variables are changed with each other.

#include <stdio.h>
 
void swapvalues(int, int);
 
int main() 
{
  int value1= 10, value2 = 20;
 
  
  swapvalues(value1, value2);
  printf("value1: %d, value2: %d\n", value1, value2);
}
 
void swapvalues(int a, int b)
{
  int temp;
  
  temp = a; 
  a = b; 
  b = temp;
}

Call by Value Output

Call by reference

The following example shows call by reference. Here we have used a pointer variable. We declare pointer variables by using the * symbol. But, when we pass the argument in a function call, we use the & operator. This will pass the memory address of the variable and not its value as in the previous example.

#include <stdio.h>
 
void swapvalues(int*, int*);
 
int main() 
{
  int value1= 10, value2 = 20;
 
  
  swapvalues(&value1, &value2);
  printf("value1: %d, value2: %d\n", value1, value2);
}
 
void swapvalues(int *a, int *b)
{
  int temp;
  
  temp = *a; 
  *a = *b; 
  *b = temp;
}
Call by Reference Output

Conclusion

C language does not support swapping. To achieve this swapping in C, we make use of the * and the & operator. This process is called by reference. We hope you understand the topic clearly. If you have any question in your mind, please ask it in the comment section. We will be happy if we can help you.

Engr. Rahamd Ullah
Engr. Rahamd Ullah
Articles: 83
Share This