Wednesday, October 13, 2010

What is Call By Reference in C

,


In C Programmings we have different ways to parameter passing schemes such as Call by Value and Call by Reference.

Call by Reference:- Reference means the address not the actual value, the address of a variable or anything. So in the call by reference we use the address of a variable instead of passing the value of a variable in the function. When we want to use address we have to use the concept of pointer because pointers have the capability to store the addresses of a variable.

In the function calling the actual arguments can send the addresses of a variables. In the function body the format arguments are to be treated as the pointers in which the address of a actual arguments are to be stored. So that the value is passed on the actual arguments are to be get by address in the formal arguments and the operations are to performed on addresses and when the control get back on the main block. These value would be remain same. Hence, result is that the changes made in the arguments are permanent.

In below example we are swapping values with Call By Reference.

Example:-

/* function definition to swap the values */
void swap(int *a, int *b)
{
   int xx;
   xx = *a;
   *a = *b;
   *b = xx;
   return;
}


#include <stdio.h>
#include <conio.h>

void swap(int *a, int *b);
int main ()
{
   int m = 60;
   int n = 80;
   printf("Before swap, value of m : %d\n", m );
   printf("Before swap, value of n : %d\n", n );

   swap(&m, &n);

   printf("After swap, value of m : %d\n", m );
   printf("After swap, value of n : %d\n", n );

   return 0;
}

0 comments to “What is Call By Reference in C”

Post a Comment