Reference parameters
- C++ course
- Beginner
- Lesson 73/116
- 5 min
Learn pass-by-reference and how changes propagate to the caller.
Reference parameters
If you declare a function parameter as a reference, the function can modify the caller's variable directly. The syntax: void addOne(int& n). The & mark says the parameter is a reference, not a copy.
So a call addOne(x) changes x itself, not a copy. Pass by value does not propagate changes; pass by reference does. Reference parameters are also used to avoid copying large objects.
Pass by value versus by reference
In pass by value, the parameter is a copy of the argument; changes inside the function do not reach the caller. In pass by reference, the parameter is an alias bound to the argument itself; changes propagate at once.
void f(int n) is by value, void f(int& n) is by reference. The only visual difference is the & mark, but the behavior is completely different. Pass by reference is also used to return more than one value from a function.
Practice The addOne function
Define a void addOne(int& n) function; in the body write n = n + 1;. In main declare int x = 5;, call addOne(x), and print x with std::cout.
Starter code
#include <iostream>
// Define the addOne function
int main() {
// Declare x
// Add an addOne call
// Print x
return 0;
}Sample solution
#include <iostream>
void addOne(int& n) {
n = n + 1;
}
int main() {
int x = 5;
addOne(x);
std::cout << x << "\n";
return 0;
}Expected output
6
Questions and answers
Review the lesson questions together with their answers. To test yourself, solve the lesson interactively.
1 What is the value of x after this code runs?
void addOne(int& n) {
n = n + 1;
}
int main() {
int x = 5;
addOne(x);
std::cout << x;
return 0;
}- 5
- 6 Correct answer
- 0
- Gives an error
Explanation: addOne(x) passes by reference, so x increases: 5 → 6.
2 Match each expression to its meaning
| Term | Meaning |
|---|---|
int& n |
Reference parameter |
addOne(x) |
Call |
n = n + 1 |
Body |
x |
Argument |
3 Reference parameter
void addOne(int____ n) { n = n + 1; }
void addOne(int& n) { n = n + 1; }
Explanation: void addOne(int& n) is pass by reference.