C Programming language

Function in C: call by value and call by reference
Previous Home Next

Call by value and call by reference

whenever we called a function and passed something to it we have always passed the ‘values’ of variables to the called function. Such function calls are called ‘calls by value’. By this what we mean is, on calling a function we are passing values of variables to it. The examples of call by value are shown below:

sum = calsum ( a, b, c ) ;
f = factr ( a ) ;
another example of 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 ;[an error occurred while processing this directive]
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.

We have also learnt that variables are stored somewhere in memory. So instead of passing the value of a variable, we can pass the location number (also called address) of the variable to a function. so it would become a ‘call by reference’. What purpose a ‘call by reference’ serves we would find out a little later. First we must equip ourselves with knowledge of how to make a ‘call by reference’. This feature of C functions needs at least an elementary knowledge of a concept called ‘pointers’.

Previous Home Next