Previous | Home | Next |
# Call by reference
We know that variables are stored somewhere in memory. So instead of passing the value of a variable to a function, we pass the address of argument then it is called Call By Reference. Inside the function, the address is used to access the actual argument.
Defining a Function: Consider the fuction swaping()
/* function definition to swap the values */ void swaping(int *a, int *b) { int c; c = *a; /* save the value at address a */ *a = *b; /* put b into a */ *b = c; /* put c into b */ return; }
Now, let us call the function swaping() bby passing values by reference as in the following example:
#include <stdio.h> /* function declaration */ void swap(int *a, int *b); int main () { /* local variable definition */ int m = 100; int n = 200; printf("Before swap, value of a : %d\n", m ); printf("Before swap, value of b : %d\n", n ); /* calling a function to swap the values. * &a indicates pointer to a ie. address of variable a and * &b indicates pointer to b ie. address of variable b. */ swap(&m, &n); printf("After swap, value of a : %d\n", m ); printf("After swap, value of b : %d\n", n ); return 0; } /* function definition to swap the values */ void swap(int *x, int *y) { int temp; temp = *x; /* save the value at address x */ *x = *y; /* put y into x */ *y = temp; /* put temp into y */ return; }
Output :
Before swap, value of a :100 Before swap, value of b :200 After swap, value of a :200 After swap, value of b :100
Previous | Home | Next |