Skip to main content

Function Argumants - Call By Reference

Call by reference in C

  • "Call by reference" in C is a method of passing arguments to a function, where the function works directly on the argument passed to it*, and any changes made to the argument within the function are reflected in the caller's scope.**

  • In other words, the function receives a reference to the original argument, rather than a copy of its value.

  • In C, "call by reference" is implemented using pointers. A pointer is a variable that holds the memory address of another variable.

  • To pass an argument by reference, the address of the argument is passed to the function, and the function operates on the argument using the pointer.

Call by reference Example in C

Here's an example of call by reference in C:

#include <stdio.h>

void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}

int main()
{
int x = 10;
int y = 20;
printf("Before calling the function: x = %d, y = %d\n", x,
y); // Print the values of x and y before the function call
swap(&x, &y); // Call the swap function with call by reference
printf("After calling the function: x = %d, y = %d\n", x,
y); // Print the values of x and y after the function call
return 0;
}
Output:

Explanation

  • The swap function takes two integer pointers a and b and swaps the values pointed to by these pointers.

  • The function uses the * operator to access the values pointed to by the pointers, and the & operator to pass the addresses of the variables x and y to the function.

  • After the function call, the values of x and y are swapped, and the change is reflected in the main function.

When to use "Call by Reference"

  • When the function needs to modify the values of its arguments: The changes should be reflected in the caller's scope. This allows the caller to use the modified values after the function call.

  • When the arguments being passed to the function are large data structures, such as arrays or structures. In such cases, passing a copy of the data structures can be very inefficient, both in terms of memory usage and processing time. By passing a reference to the data structure, the function can modify it directly, without the need to create a copy.

  • When multiple values need to be returned from a function. In C, a function can only return a single value, but using call by reference, multiple values can be returned through the arguments passed to the function.

  • Call by reference can also be used to implement pass-by-pointer, which is a technique for passing pointer values as arguments to a function. This can be useful for passing arrays or dynamic data structures to a function.

danger

"Call by reference" is a powerful technique for passing arguments to functions, but it can also lead to bugs and security vulnerabilities if not used properly.