How to Pass by Reference in C++: Syntax and Examples
In C++, you pass by reference by using
& in the function parameter, like void func(int &x). This allows the function to modify the original variable directly without copying it.Syntax
To pass a variable by reference, add & after the type in the function parameter. This means the function receives the original variable, not a copy.
- Type &name: Declares a reference parameter.
- Function call: Pass the variable normally without
&.
cpp
void updateValue(int &num) { num = 10; // changes original variable }
Example
This example shows how a function changes the original variable by passing it by reference.
cpp
#include <iostream> void updateValue(int &num) { num = 10; // modifies original variable } int main() { int a = 5; std::cout << "Before: " << a << std::endl; updateValue(a); std::cout << "After: " << a << std::endl; return 0; }
Output
Before: 5
After: 10
Common Pitfalls
Common mistakes when passing by reference include:
- Forgetting the
&in the function parameter, which causes pass-by-value (copy) instead. - Trying to pass literals or temporary values by reference, which is not allowed.
- Confusing pointers and references; references are safer and simpler to use.
cpp
/* Wrong: pass by value, original not changed */ void wrongFunc(int num) { num = 20; } /* Correct: pass by reference, original changed */ void correctFunc(int &num) { num = 20; }
Quick Reference
| Concept | Syntax | Effect |
|---|---|---|
| Pass by value | void func(int num) | Function gets a copy, original not changed |
| Pass by reference | void func(int &num) | Function gets original, can modify it |
| Pass by const reference | void func(const int &num) | Function gets original, cannot modify it |
Key Takeaways
Use
& in function parameters to pass variables by reference in C++.Passing by reference lets functions modify the original variable directly.
Always pass variables normally when calling; no special syntax needed.
Avoid passing literals or temporary values by non-const reference.
Use const references to avoid copying without allowing modification.