Call by Reference

Recall when we wanted to swap two values using a function we were unable to actually swap the calling parameters as the call by value standard was employed. The solution to the problem is to use call by reference which is implemented in C by using pointers as is illustrated in the following example.

#include <stdio.h>
void swap( int *, int * ) ;
void main( )
{
int a, b ;
printf( "Enter two numbers" ) ;
scanf( " %d %d ", &a, &b ) ;
printf( "a = %d ; b = %d \n", a, b ) ;
swap( &a, &b ) ;
printf( "a = %d ; b = %d \n", a, b ) ;
}
void swap ( int *ptr1, int *ptr2 )
{
int temp ;
temp = *ptr2 ;
*ptr2 = *ptr1 ;
*ptr1 = temp ;
}

The swap() function is now written to take integer pointers as parameters and so is called in main() as
swap( &a, &b ) ;
where the addresses of the variables are passed and copied into the pointer variables in the parameter list of swap(). These pointers must be de-referenced to manipulate the values, and it is values in the the same memory locations as in main() we are swapping unlike the previous version of swap where we were only swapping local data values.
In our earlier call-by-value version of the program we called the function from main() as swap(a,b); and the values of these two calling arguments were copied into the formal arguments of function swap.
In our call-by-reference version above our formal arguments are pointers to int and it is the addresses contained in these pointers, (i.e. the pointer values), that are copied here into the formal arguments of the function. However when we de-reference these pointers we are accessing the values in the main() function as their addresses do not change.
Call by Reference Call by Reference Reviewed by Unknown on 04:42 Rating: 5

No comments:

Powered by Blogger.