Call by Value vs Call by Reference in C++ tutorial
Call by Value vs Call by Reference in C++ , cplus tutorial
In C++, function arguments can be passed in two main ways: Call by Value and Call by Reference. Understanding the difference between them is crucial for writing efficient and predictable programs.
In Call by Value, a copy of the actual argument is passed to the function. Changes made inside the function do not affect the original variable.
Key Points:
Passes a copy of the value.
Original data remains unchanged.
Requires more memory for copies.
Example:
#include <iostream>
using namespace std;
void modify(int x) {
x = 20;
}
int main() {
int num = 10;
modify(num);
cout << "Value of num: " << num << endl;
return 0;
}
Output:
Value of num: 10
In Call by Reference, the address of the actual argument is passed to the function. Changes made inside the function directly affect the original variable.
Key Points:
Passes a reference (memory address).
Original data is modified.
More memory-efficient than call by value.
Example:
#include <iostream>
using namespace std;
void modify(int &x) {
x = 20;
}
int main() {
int num = 10;
modify(num);
cout << "Value of num: " << num << endl;
return 0;
}
Output:
Value of num: 20
Another way is passing pointers, which also modifies the original variable.
void modify(int *x) {
*x = 20;
}
| Feature | Call by Value | Call by Reference |
|---|---|---|
| Data passed | Copy of actual data | Address of actual data |
| Effect on original data | No change | Can be modified |
| Memory usage | Higher (creates copies) | Lower (uses same variable) |
| Use case | When you don’t want changes | When you want to modify |
Use call by value when you want to protect the original data.
Use call by reference for large data (like arrays/objects) to improve performance.
Prefer const references if you want to avoid copying but don’t want modification.