0
4.8kviews
Explain call by value and call by reference with necessary example
1 Answer
0
190views

Call by value

In call by value mechanism, the called function creates a new set of variables in stack and copies the values of the arguments into them. Example: Program showing the Call by Value mechanism.

Call by value source code

1   

 2  void swap(int x, int y)

 3   { 

 4     int z;

 5     z = x;

 6     x = y;

 7     y = z;

 8     printf("Swapped values are a = %d and b = %d", x, y);

 9   }

 10     

 11     int main (int argc, char *argv[])

 12      {

 13        int a = 7, b = 4;

 14        printf("Original values are a = %d and b = %d", a, b);

 15        swap(a, b);

 16        printf("The values after swap are a = %d and b = %d", a, b);

 17     }

Output

  -        Original Values are a = 7 and b = 4

  -        Swapped values are a = 4 and b = 7

  -        The values after swap are a = 7 and b = 4

This happens because when function swap() is invoked, the values of a and b gets copied onto x and y. The function actually swaps x and y while the values of the original variables a and b remain intact. oint to note is x and y are in stack. Value of a and b will be copied to x and y. Inside swap() value of x and y will be interchanged but it will not affect a and b in the main(). Please note a and b are located at the context of main() whereas x and y located at thecontext of swap(). When swap() function returns, this context of x and y will be lost and it will again come back to the context of a and b.

Call by reference

In call by reference mechanism, instead of passing values to the function being called, references/pointers to the original variables are passed. Example: Program interchange values of two variables by call by reference mechanism.

Call by reference source code

 1  

 2  void swap(int *x, int *y)

 3   {

 4     int z;

 5     z = *x;

 6     *x = *y;

 7     *y = z;

 8     printf("Swapped values are a = %d and b = %d", *x, *y);

 9   }

 10     int main (int argc, char *argv[])

 11      {

 12        int a = 7, b = 4;

 13        printf("Original values are a = %d and b = %d", a, b);

 14        swap(&a, &b);

 15        printf("The values after swap are a = %d and b = %d", a, b);

 16      }

Output

 1     Original Values are a = 7 and b = 4

 2     Swapped values are a = 4 and b = 7

 3     The values after swap are a = 4 and b = 7

This happens because when function swap() is invoked, it creates a reference for the first incoming integer a in x and the second incoming integer b in y. Hence the values of the original variables are swapped.

Please log in to add an answer.