Difference Between Call by Value and Call by Reference in C
Call by value and call by reference are two ways of passing arguments to functions in C. They differ in how data is handled and whether changes inside a function affect the original variables.
What is Call by Value?
In call by value, a copy of the actual parameter is passed to the function. Changes made inside the function do not affect the original variable.
C
// Call by value example
#include <stdio.h>
void modify(int x) {
x = 20;
}
int main() {
int a = 10;
modify(a);
printf("%d", a); // Output: 10
return 0;
}
What is Call by Reference?
In call by reference, the address of the variable is passed to the function using pointers. Changes made inside the function affect the original variable.
C
// Call by reference example
#include <stdio.h>
void modify(int *x) {
*x = 20;
}
int main() {
int a = 10;
modify(&a);
printf("%d", a); // Output: 20
return 0;
}
Key Differences Between Call by Value and Call by Reference
- Call by value passes copy, call by reference passes address
- Changes do not affect original in value, but affect in reference
- Call by value is safer, call by reference is more flexible
- Call by reference uses pointers
- Memory usage differs due to copying
Comparison Table
| Feature | Call by Value | Call by Reference |
|---|---|---|
| Data Passed | Copy | Address |
| Effect on Original | No change | Changes |
| Memory | More (copy) | Less |
| Safety | High | Lower |
| Usage | Simple functions | Modify data |
Swap Example
C
// Swap using call by reference
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
When to Use Call by Value?
- When original data should not change
- For small data values
- For safe function calls
- When no side effects are desired
When to Use Call by Reference?
- When modifying original data
- For large data structures
- To return multiple values
- For performance optimization
Real-World Applications
- Call by value in calculations
- Call by reference in swapping values
- Reference in data structures
- Value in simple utilities
- Both used in system programming
Common Mistakes to Avoid
- Forgetting to use pointers in reference
- Dereferencing errors
- Unintended variable modification
- Passing wrong arguments
- Pointer misuse
Advanced Concepts
- Pointer to pointer
- Passing arrays to functions
- Const correctness
- Function pointers
- Memory optimization
Practice Exercises
- Implement swap using both methods
- Pass array to function
- Modify structure using reference
- Compare performance
- Return multiple values using pointers
Conclusion
Call by value and call by reference are essential concepts in C. Call by value ensures safety, while call by reference provides flexibility and efficiency. Choosing the right approach depends on your program requirements.
Note: Note: Use call by value for safety and call by reference when modification is required.
Codecrown