Call by Reference in C

In call by reference method of parameter passing, the address of the actual parameters is passed to the function as the formal parameters. In C, we use pointers to achieve call-by-reference.

  • Both the actual and formal parameters refer to the same locations.
  • Any changes made inside the function are actually reflected in the actual parameters of the caller.

Example of Call by Reference

The following C program is an example of a call-by-reference method.

C




// C program to illustrate Call by Reference
#include <stdio.h>
 
// Function Prototype
void swapx(int*, int*);
 
// Main function
int main()
{
    int a = 10, b = 20;
 
    // Pass reference
    swapx(&a, &b); // Actual Parameters
 
    printf("Inside the Caller:\na = %d b = %d\n", a, b);
 
    return 0;
}
 
// Function to swap two variables
// by references
void swapx(int* x, int* y) // Formal Parameters
{
    int t;
 
    t = *x;
    *x = *y;
    *y = t;
 
    printf("Inside the Function:\nx = %d y = %d\n", *x, *y);
}


Output

Inside the Function:
x = 20 y = 10
Inside the Caller:
a = 20 b = 10

Thus actual values of a and b get changed after exchanging values of x and y.

Difference Between Call by Value and Call by Reference in C

Functions can be invoked in two ways: Call by Value or Call by Reference. These two ways are generally differentiated by the type of values passed to them as parameters.

The parameters passed to the function are called actual parameters whereas the parameters received by the function are called formal parameters.

Similar Reads

Call By Value in C

In call by value method of parameter passing, the values of actual parameters are copied to the function’s formal parameters....

Call by Reference in C

...

Difference between the Call by Value and Call by Reference in C

In call by reference method of parameter passing, the address of the actual parameters is passed to the function as the formal parameters. In C, we use pointers to achieve call-by-reference....

Conclusion

...