Call by reference is the second way of passing arguments to a subroutine. In this method, the address of an argument is copied into the parameter. Inside the subroutine, the address is used to access the actual argument used in the call. This means that changes made to the parameter affect the argument.
C uses call by value for passing parameters, you can create a call by reference by passing a pointer to an argument, instead of passing the argument itself. Since the address of the argument is passed to the function, code within the function can change the value of the argument outside the function.
Pointers are passed to functions just like any other argument. Of course, you need to declare the parameters as pointer types.
\* C Program to demonstrate Call by Reference *\
# include < stdio.h >
int swap ( int *x, int *y) ;
int main( )
{
int i = 10, j = 20 ;
printf("i and j before swapping: %d %d \n", i, j) ;
swap( &i, &j ) ;
printf(" i and j after swapping: %d %d \n", i, j) ;
return ( 0 ) ;
}
void swap ( int *x, int *y)
{
int temp ;
temp = *x ;
*x = *y ;
*y = temp ;
}
i and j before swapping: 10 20
i and j after swapping: 20 10
The swap( ) function is able to exchange the values of the two variables pointed to by x and y because their addresses (not their values) are passed. Within the function, the contents of the variables are accessed using standard pointer operations, and their values are swapped.
This program manages to exchange the values of a and b using their addresses stored in x and y.