đ Call by Value vs Call by Reference in C
In C programming, when we pass arguments to a function, they can be passed in two ways: Call by Value and Call by Reference. Understanding the difference between them is essential for mastering function behavior.
đ Call by Value (Default in C)
In Call by Value, the function gets a copy of the actual argument. Changes made inside the function do not affect the original variable.
✅ Example:
#include <stdio.h>
void update(int n) {
n = n + 10;
printf("Inside function: %d\n", n);
}
int main() {
int num = 20;
update(num);
printf("Outside function: %d\n", num);
return 0;
}
đ Output:
Inside function: 30 Outside function: 20
Explanation: The original num
in main()
is unchanged because n
was just a copy.
đ Call by Reference (Using Pointers)
C does not support call by reference directly, but you can simulate it using pointers. This allows the function to modify the actual value of the argument.
✅ Example:
#include <stdio.h>
void update(int *n) {
*n = *n + 10;
printf("Inside function: %d\n", *n);
}
int main() {
int num = 20;
update(&num);
printf("Outside function: %d\n", num);
return 0;
}
đ Output:
Inside function: 30 Outside function: 30
Explanation: The function changed the value at the memory address of num
. So the original variable is updated.
⚖️ Difference Table
Feature | Call by Value | Call by Reference |
---|---|---|
Argument Type | Copy of variable | Address of variable |
Original Value Changed? | No | Yes |
Safety | Safer (no accidental modification) | Less safe (can change original) |
Speed | Slower with large data | Faster with large data |
đ§ Summary
- Call by Value → Passes a copy → No change in original
- Call by Reference → Passes address → Original changes
- Use pointers in C to simulate call by reference
đ§Š Practice Ideas
- Write a function to swap two numbers using call by value (see if it works).
- Write a swap function using call by reference.
- Create a function that increments a number using pointer.
āĻোāύ āĻŽāύ্āϤāĻŦ্āϝ āύেāĻ:
āĻāĻāĻি āĻŽāύ্āϤāĻŦ্āϝ āĻĒোāϏ্āĻ āĻāϰুāύ