Call by reference: In the call by reference method, instead of passing values to the function being called, references/pointers to the original variables are passed.

Example: Program showing the Call by Reference method


void swap(int *x, int *y)
{
  int temp;
  temp = *x;
  *= *y;
  *= temp;
  printf("Swapped values are a = %d and b = %d", *x, *y);
}
int main (int argc, char *argv[])
{
  int a = 7, b = 4;
  printf("Original values are a = %d and b = %d", a, b);
  swap(&a, &b);
  printf("The values after swap are a = %d and b = %d", a, b);
}
  
Output:
  Original Values are a = 7 and b = 4
  Swapped values are a = 4 and b = 7
  The values after swap are a = 4 and b = 7


In the above example, swap has been called with the values address of a and address of b. Swap function copies the value of x(i.e. value of a) and saves it in temp. Then value of y(i.e. value of b) is used to overwrite the value of 'a' using original address of a(i.e. value of x). Then value of y(i.e. value of b) itself is overwritten by temp. Here both a and b have been referenced by the original address thus original values has been swapped.

Here is the block diagram describing disassembly steps, call stack and argument variables. Calling swap (&a, &b) can be split into some assembly steps like-

  1. push address of b
  2. push address of a
  3. save return address
  4. call function

Call by reference - describing disassembly steps, call stack and argument variables

Here one point to note is x and y are pointers. Address of a and b will be copied to x and y. Inside swap() value of *x and *y will be interchanged which is same as changing a and b in the main().

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#