C++ Call by Reference
In C++, call by reference passes the actual variable to the function using a reference. Changes made inside the function affect the original variable in the caller.
1. Call by Reference Syntax
The function receives a reference to the argument using the & symbol, allowing modifications to affect the original variable.
C++
return_type function_name(data_type ¶meter) {
// function body
}
2. Call by Reference Example
This example demonstrates call by reference where changes inside the function modify the original variable.
C++
#include <iostream>
using namespace std;
void increment(int &a) {
a = a + 1;
cout << "Inside function: " << a << endl;
}
int main() {
int x = 5;
increment(x);
cout << "Outside function: " << x << endl;
return 0;
}
3. Common Mistakes
Forgetting the & in the function parameter or expecting call by reference behavior in call by value are common mistakes. Always use & to modify the original variable.
Conclusion
C++ call by reference allows functions to modify the original variables. It is useful when you want functions to change data directly or avoid copying large objects.
Codecrown