C-Call by Reference

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 ;

}

 

error: Content is protected !!