Call by Value vs Call by Reference in C Programming (With Simple Examples)
Call by Value vs Call by Reference in C Programming (With Simple Examples)
One of the most confusing topics for beginners in C programming is the difference between call by value and call by reference.
This concept is extremely important because it affects how functions work and how data is modified inside a program.
In this article, we will clearly explain call by value vs call by reference in C using simple language and easy examples.
What Is a Function Call?
When a function is called, values are passed from the calling function to the called function.
The way these values are passed decides whether the original data can be modified or not.
What Is Call by Value?
In call by value, a copy of the variable’s value is passed to the function.
Changes made inside the function do not affect the original variable.
Example of Call by Value
void change(int x) {
x = 20;
}
int main() {
int a = 10;
change(a);
printf("%d", a);
}
The output will be 10 because only a copy was modified.
Disadvantages of Call by Value
- Original data cannot be changed
- More memory usage due to copying
What Is Call by Reference?
In call by reference, the address of the variable is passed to the function.
This allows the function to modify the original variable.
Example of Call by Reference
void change(int *x) {
*x = 20;
}
int main() {
int a = 10;
change(&a);
printf("%d", a);
}
The output will be 20 because the original variable was modified.
Advantages of Call by Reference
- Original data can be changed
- Efficient memory usage
- Useful for large data structures
Key Differences Between Call by Value and Call by Reference
| Call by Value | Call by Reference |
|---|---|
| Passes copy of value | Passes address of variable |
| Original variable not modified | Original variable modified |
| No pointers used | Pointers required |
| Less efficient for large data | More efficient |
Real-Life Example
Call by value is like giving someone a photocopy of a document.
Call by reference is like giving someone the original document.
When to Use Call by Value?
- When you don’t want data modification
- For simple and small variables
When to Use Call by Reference?
- When you need to modify original data
- For arrays, structures, and large data
Interview Importance
This topic is frequently asked in interviews to test understanding of pointers and memory.
Final Conclusion
Understanding the difference between call by value and call by reference is essential for writing correct and efficient C programs.
Once you master this concept, working with functions and pointers becomes much easier.
Next Post: Arrays vs Pointers in C (Explained with Examples)
Comments
Post a Comment