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);
10  int main (int argc, char *argv[])
11  {
12    int a = 7, b = 4;
13    printf("Original values are a = %d and b = %d", a, b);
14    swap(&a, &b);
15    printf("The values after swap are a = %d and b = %d", a, b);
16  }
18  Output:
19    Original Values are a = 7 and b = 4
20    Swapped values are a = 4 and b = 7
21    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().

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

 Vote 0

Similar topics related to this section

calling conventions, calling convention of C,C++ and PASCAL, library function linking, call-by-value and call-by-reference, parameter passing call-by-value, parameter passing call-by-reference, structure as function argument, array as function argument, inline-functions, macro vs inline-function,

# C Programming Language (Prentice Hall Software)
# Let Us C Paperback - 2006 by Yashavant Kanetkar
# Understanding and Using C Pointers Core techniques for memory management
# Data Structures Using C and C++ Paperback - 1998
# Data Structures In C Paperback - August 11, 2008 by Noel Kalicharan