Passing argument to a function by reference is also know as call by reference. In this method if we change the parameter given in the function will effect the argument. For passing a value by reference, we use pointers. As we use pointers in call by reference, so arguments address are passed rather than the value.
Below is the example of how to pass argument by reference.
// function definition for swapping two integer type values a and b
void swap(int *a, int *b)
{
int t;
t = *a; // save the value at address a into t variable
*a = *b; // we put value of b into a
*b = t; // put t into b
return;
}
Now, we call the function swap() by passing original values .
#include <stdio.h>
void swap(int *a, int *b);
int main () {
int x = 5; // local variable definition
int y = 6;
printf("Before swap, value of x : %d\n", x );
printf("Before swap, value of y : %d\n", y );
// Now we are calling a function to swap two values
swap(x, y);
printf("After swap value of x : %d\n", x );
printf("After swap value of y : %d\n", y );
return 0;
}
**OUTPUT**
Before swap value of x :5
Before swap value of y :6
After swap value of x :6
After swap value of y :5
This shows that if we change parameter which are given inside a function will effect the argument
0 Comment(s)