Pass by reference in C
Pass by Reference
Pass by reference in C refers to passing the memory address (i.e., reference) of a variable to a function instead of the value.
This allows the function to modify the original variable in memory, rather than just working with a copy of the value.
In C, pass by reference is implemented using pointers. A pointer to a variable is passed to the function, which can then modify the value of the variable by dereferencing the pointer.
Example
Program below demonstrates pass by reference in C:
#include <stdio.h>
// Function that takes a pointer to an int
void increment(int *num)
{
(*num)++; // dereference the pointer and increment the value
}
int main()
{
int num = 0;
printf("num = %d\n", num); // prints "num = 0"
increment(&num); // pass a pointer to the "num" variable
printf("num = %d\n", num); // prints "num = 1"
return 0;
}
Output:
Explanation
- The increment function takes a pointer to an
int
as an argument. - Inside the function, the pointer is dereferenced using the
*
operator, and the value of the variable is incremented. - When
increment(&num)
is called in themain
function, a pointer to thenum
variable is passed as an argument. - The increment function then modifies the value of the
num
variable in memory, and the updated value is printed in themain
function.