Call by Value vs Call by Reference in C: Key Differences and Examples
call by value passes a copy of the variable to a function, so changes inside the function do not affect the original variable. Call by reference passes the variable's address (pointer), allowing the function to modify the original variable directly.Quick Comparison
Here is a quick comparison of call by value and call by reference in C:
| Factor | Call by Value | Call by Reference |
|---|---|---|
| What is passed? | A copy of the variable's value | The address (pointer) of the variable |
| Effect on original variable | No change | Can be changed |
| Memory usage | Uses extra memory for copy | Uses less memory, passes address |
| Safety | Safer, original data protected | Less safe, can modify original data |
| Use case | When original data should not change | When function needs to modify original data |
| Syntax | Simple variable | Pointer variable |
Key Differences
Call by value means the function receives a copy of the variable's value. Any changes made inside the function affect only the copy, so the original variable outside the function remains unchanged. This is simple and safe because the original data is protected from accidental modification.
In contrast, call by reference means the function receives the address of the variable using pointers. The function can then directly access and modify the original variable's value. This allows functions to change variables outside their own scope but requires careful handling of pointers to avoid errors.
Because C does not support call by reference natively, programmers simulate it by passing pointers. This difference affects how you write and understand functions that need to modify variables passed to them.
Code Comparison
This example shows call by value where the function tries to change a variable but the original stays the same.
#include <stdio.h> void addTen(int num) { num = num + 10; printf("Inside function: %d\n", num); } int main() { int x = 5; addTen(x); printf("Outside function: %d\n", x); return 0; }
Call by Reference Equivalent
This example shows call by reference using pointers to modify the original variable.
#include <stdio.h> void addTen(int *num) { *num = *num + 10; printf("Inside function: %d\n", *num); } int main() { int x = 5; addTen(&x); printf("Outside function: %d\n", x); return 0; }
When to Use Which
Choose call by value when you want to protect the original data from changes and only need to use the value inside the function. It is simpler and safer for read-only operations.
Choose call by reference when the function needs to modify the original variable or when passing large data structures to avoid copying overhead. It is essential for functions that must update multiple values or return results via parameters.