Computer >> Computer tutorials >  >> Programming >> C programming

Difference between Call by Value and Call by Reference


In programming on the basis of passing parameters to a function we classified function invocation into two : Call by value and Call by reference.As name suggest in both invocations we are calling function by type of parameters in one we are passing actual value of parameter and in other we are passing the location/reference of parameter.

Following are the important differences between Call by Value and Call by Reference.

Sr. No.KeyCall by ValueCall by Reference
1Naming ConventionAs in this type the value of parameter is get passed for function invocation hence it is named as Call by Value.On other hand in this type the reference of parameter is get passed for invoking the function so it is named as Call by Reference.
2Internal implementationIn Call by value the value of parameter we passed during calling of function are get copied to the actual local argument of the function.In Call by reference the location address/reference of passed parameter is get copied and assigned to the local argument of the function so both passed parameter and actual argument refers to the same location.
3Effects of changesAs value of passed parameter is copied to argument of function so any change done in argument inside the function do not get reflected in the passed parameter.As both argument and passed parameter refers to the same location hence any change done to argument inside the function get reflected in the passed parameter.
4Referred Memory locationMemory location referred both passed parameter and actual arguments of function is different.Memory location referred by both passed parameter and actual argument of function is same.
5Supported languages.Call by value is get supported by languages such as : C++.PHP. Visual Basic NET, and C#.Call by reference is primarily get supported by JAVA.

Example of Call by value vs Call by reference

ByValue.c

#include <stdio.h>
class ByValue{
   void swapByValue(int, int); /* Prototype */
   int main(){
      int n1 = 10, n2 = 20;
      swapByValue(n1, n2);
      printf("n1: %d, n2: %d\n", n1, n2);
   }
   void swapByValue(int a, int b){
      int t;
      t = a; a = b; b = t;
   }
}

Output

n1: 10, n2: 20

Example

ByReference.c

#include <stdio.h>
class ByReference{
   void swapByReference(int*, int*);
   int main(){
      int n1 = 10, n2 = 20;
      swapByReference(&n1, &n2);
      printf("n1: %d, n2: %d\n", n1, n2);
   }
   void swapByReference(int *a, int *b){
      int t;
      t = *a; *a = *b; *b = t;
   }
}

Output

n1: 20, n2: 10