This blog is under construction

Monday, 30 December 2013

Call by value vs call by reference

Difference between call by value and call by reference
There are two types of parameter passing schemes.
     1. Call by value
     2. Call by reference

Call by Value:
     A copy of actual arguments are passed to the formal arguments.  So, any modification to formal arguments won't affect the original value of actual arguments.

Example C program to illustrate call by value:
 
  #include <stdio.h>
  /* swaps given two number */
  void swap(int a, int b) {
        int tmp;
        tmp = a;
        a = b;
        b = tmp;
        printf("Inside swap() -> a = %d\tb = %d\n", a, b);
        return;
  }

  int main() {
        int a, b;
        printf("Enter two integers: ");
        scanf("%d%d", &a, &b);
        swap(a, b); // pass by value
        printf("Inside main() -> a = %d\tb = %d\n", a, b);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter two integers: 10 20
  Inside swap() -> a = 20 b = 10
  Inside main() -> a = 10 b = 20



Call by Reference:
Here, the address of variables are passed from the actual argument to the formal argument.  So, the called function acts on addresses rather than values.  Here, the formal arguments have the pointer to the actual arguments. So, any change made to formal arguments reflect on actual arguments.

Example C program to illustrate call by reference
 
  #include <stdio.h>
  /* swaps given two number */
  void swap(int *a, int *b) {
        int tmp;
        tmp = *a;
        *a = *b;
        *b = tmp;
        printf("Inside swap() -> *a = %d\t*b = %d\n", *a, *b);
        return;
  }

  int main() {
        int a, b;
        printf("Enter two integers: ");
        scanf("%d%d", &a, &b);
        /* address of variable is passed to swap() */
        swap(&a, &b);  // pass by reference
        printf("Inside main() ->  a = %d\t b = %d\n", a, b);
        return 0;
  }

  Output:
  jp@jp-VirtualBox:~/$ ./a.out
  Enter two integers: 10 20
  Inside swap() -> *a = 20 *b = 10
  Inside main() ->  a = 20 b = 10



No comments:

Post a Comment