What is a call by Reference in C ?
Call by reference is a method of passing arguments to a function in which the address of the argument is passed, rather than its value. This means that any changes made to the parameter within the function are reflected in the argument outside the function.
In C, call by reference is implemented using pointers. To pass an argument by reference, a pointer to the variable must be passed to the function. The function then uses the pointer to access and manipulate the value stored at that memory location.
Here is an example of a function that takes two integer arguments passed by reference and swaps their values:
#include<stdio.h>
void swap(int *,int *);
int main()
{
int x = 5, y = 10;
swap(&x, &y);
printf("x: %d, y: %d", x, y); // Output: x: 10, y: 5
return 0;
}
void swap(int *a, int *b)
{
int temp = *a;
*a = *b;
*b = temp;
}
In this example, the function "swap" takes two pointers to integers as arguments. The function uses the dereference operator (*) to access the values stored at the memory locations pointed to by the pointers, and then swaps their values using a temporary variable.
When the function is called in the main() with the variables x,y the values are passed by reference and the values are changed inside the function and the same is reflected in the main function as well.