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

  1. #include <conio.h>
  2. #include <stdio.h>
  3. void main()
  4. {
  5. int a=1,b=2;
  6. clrscr();
  7. printf("\nOriginal values of a:%d, b:%d",a,b);
  8. swap(&a,&b);
  9. printf("\n",a,b);
  10. getch();
  11. }
  12. swap(int *x, int *y)
  13. {
  14. int temp = *x;
  15. *x=*y;
  16. *y=temp;
  17. printf("\nSwaped values in swap function a:%d,b:%d",*x,*y);
  18. return 0;
  19. }

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.