Call by Reference
Definition
Passing actual address of variables from the caller funtion to the function definition is called as call by reference or passing by reference.
Description
- Here '&' ampersand symbol is used before the argument in caller function to pass actual address location number of the argument and at function definition '*' operator symbol is used as a pointer to access the value of the argument.
- Change in the value of variables in definition function will affect the value of variables from were you passed in.
swap(&a,&b); //caller function with actual arguments
.
.
.
swap(int *x, int *y) //function definition with formal arguments
{
//function body
}
When to use
When there is need to change the values of variables in the calling function or program.
Source code
- #include <conio.h>
- #include <stdio.h>
- void main()
- {
- int a=1,b=2;
- clrscr();
- printf("\nOriginal values of a:%d, b:%d",a,b);
- swap(&a,&b);
- printf("\n",a,b);
- getch();
- }
- swap(int *x, int *y)
- {
- int temp = *x;
- *x=*y;
- *y=temp;
- printf("\nSwaped values in swap function a:%d,b:%d",*x,*y);
- return 0;
- }
Output
Original values of a:1, b:2
Swaped values in swap function a:2,b:1
After swaping the values of a:2, b:1
Program working steps
- First 2 lines are preprocessor directives which include defintion of functions like clrscr(), printf() etc.
- Void main function, from where the program execution starts.
- Declaration of two variables a and b with integer data-type.
- clrscr() fucntion to clear the screen like cls in windows and clear in linux.
- Printing of original values a and b before swapping.
- swap(&a,&b); caller function with two arguments passes address location number of the value using '&' ampersand operator.
- By invoking the swap caller function the program control transfers to line no.13.
- swap function definition contains two arguments declared with integer pointer x and y. The address(reference) which is passed from the caller function is stored in these two pointer variables x and y.
- Variable temp is used for temporary storage to swap the values of x and y.
- Line no.15 int temp = *x; statement assigns the value stored at location address specified in *x into the variable temp. In the same way next two statement are evaluated by the compiler.
- Swaped values of a and b in swap function are then printed and program control is transfered back to main function using return 0; statement.
- After returning back to main function swap values of a and b are printed once again.
- getch() function to wait for user to exit from the program.
- From output of the program you can learn that when you modify the values using pass by reference to a function, then there is also change in the value of the variables from the calling function.