Functions - Example on Pass By Reference

Example on Pass By Reference :

/* Program to swap the values of two variables */

 # include < stdio.h >
Swap ( p, q )
int *p, *q;
{
int t;
t = *p;
*p = *q;
*q = t;
}

main( )
{
int x, y;
printf ( " \n Enter the value for x and y " );
scanf ( " %d%d", &x, &y );

printf ( " \n Before calling swapping x = %d \n y = %d ",x, y );
Swap ( &x, &y );
printf(" \n After calling swapping x = %d \n y = %d ", x, y );
 

}
                 In the above program, a function call Swap ( &x, &y ) indicates that we are passing address of x and y variables to Swap function. It is received by pointer variables *p and *q means the address of x and y are stored in pointer p and q respectively. In function definition values are interchanged. As arguments are passed by reference changes are automatically effected to actual arguments.

Comments