Fundamentals of Computer Programming - Old Questions

8. Differentiate between call by value and call by reference with example.

6 marks | Asked in 2073

In call by value, a copy of actual arguments is passed to formal arguments of the called function and any change made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function. 

In call by reference, the location (address) of actual arguments is passed to formal arguments of the called function. This means by accessing the addresses of actual arguments we can alter them within from the called function.

In call by value, actual arguments will remain safe, they cannot be modified accidentally whereas In call by reference, alteration to actual arguments is possible within from called function; therefore the code must handle arguments carefully else you get unexpected results.

Example using Call by Value:

#include <stdio.h>

void swapByValue(int, int); /* Prototype */

int main() /* Main function */

{

  int n1 = 10, n2 = 20;

  /* actual arguments will be as it is */

  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;

}

Example using Call by Reference:

#include <stdio.h>

void swapByReference(int*, int*); /* Prototype */

int main() /* Main function */

{

  int n1 = 10, n2 = 20;

  /* actual arguments will be altered */

  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;

}