Function Calls in C

The two types of function calls—call by value and call by reference. Arguments can generally be passed to functions in one of the two ways

  • sending the values of the arguments
  • sending the addresses of the arguments

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

In the second method (call by reference) 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

Leave a Comment