When we write functions in C, we often need to pass data from one function to another. Sometimes we just want the function to use the data without changing it, while other times we want the function to modify the original data. So there are two ways to pass parameters to functions.
Please note that the C language only supports pass by value. We achieve pass by reference effect with the help of pointer feature of C. In C++, we can either use pointers or references for pass-by-reference.
Pass by Value
In pass by value, the function receives a copy of the variable's value.
- Any changes made to the parameter inside the function do not affect the original variable in the caller.
- Two separate copies exist in memory: The original variable in the caller and the function's local copy
#include <stdio.h>
// Function using pass by value
void updateValue(int y)
{
// y is a local copy of x; changes here do not affect x in main
y = y + 10;
}
int main()
{
int x = 50;
printf("Before function call: %d\n", x);
// Passes a copy of original
updateValue(x);
// original remains unchanged
printf("After function call: %d\n", x);
return 0;
}
Output
Before function call: 50 After function call: 50
Pass by Reference
In pass by reference, the function receives the address of the variable instead of a copy.
- The function can directly modify the original variable in the caller.
- Only one memory location exists for the variable, so changes inside the function affect the original variable.
- In C, this is done using pointers, as C does not have pass by reference like C++. Instead, you can pass the address of a variable to a function using pointers.
#include <stdio.h>
// Function using pass by reference (via pointer)
void updateValue(int *y)
{
// Modifies the original variable using its address
*y = *y + 10;
}
int main()
{
int x = 50;
printf("Before function call: %d\n", x);
// Passes the address of x
updateValue(&x);
// Original variable is changed
printf("After function call: %d\n", x);
return 0;
}
Output
Before function call: 50 After function call: 60
Difference between Pass By Value and Pass By Reference
Pass By Value | Pass By Reference |
|---|---|
A copy of the variable is passed in the function. | The address of the variable is passed in the function. |
Original variable is not affected. | Changes are reflected in the original variable. |
Two separate memory locations exist (original + function copy) | Only one memory location is shared. |
Function parameter is a normal variable | Function parameter is a pointer (*) |
Use when you want to protect original data. | Use when you want to modify original data. |
Example: void func( int x) | Example: void func(int *x) |