Call by Value and call by Reference


Two types of Function Calls

The two types of function calls are : call by value and call by reference.

Arguments can generally be passed to functions in one of the two ways:

(a) sending the values of the arguments

(b) sending the addresses of the arguments

Call by Value :

In the first method the ‘value’ of each of the actual arguments in the calling function is copied into corresponding formal arguments of the called function.
With this method the changes made to the formal arguments in the called function have no effect on the values of actual arguments in the calling function.

The following program illustrates the ‘Call by Value’.

main( )
{
int a = 10, b = 20 ;
swapv ( a, b ) ;
printf ( "\na = %d b = %d", a, b ) ;
}
swapv ( int x, int y )
{
int t ;
t = x ;
x = y ;
y = t ;
printf ( "\nx = %d y = %d", x, y ) ;
}

The output of the above program would be :

x = 20 y = 10
a = 10 b = 20

Note that values of a and b remain unchanged even after exchanging the values of x and y.

Call by Reference :

In this the addresses of actual arguments in the calling function are copied into formal
arguments of the called function.
This means that using these addresses we would have an access to the actual arguments and hence we would be able to manipulate them.

The following program illustrates this fact.

main( )
{
int a = 10, b = 20 ;
swapr ( &a, &b ) ;
printf ( "\na = %d b = %d", a, b ) ;
}
swapr( int *x, int *y )
{
int t ;
t = *x ;
*x = *y ;
*y = t ;
}

The output of the above program would be:
a = 20 b = 10

Note that this program manages to exchange the values of a and b using their addresses stored in x and y.

Usually in C programming we make a call by value. This means that in general you cannot alter the actual arguments.
But if desired, it can always be achieved through a call by reference.

     Prev                                                   NEXT

0 comments:

Post a Comment