C++ functions and references
Use a reference parameter to update a caller's value.
C++
#include <iostream>
#include <cassert>
void add_bonus(int& score, int bonus) {
score += bonus;
}
int main() {
int score = 80;
add_bonus(score, 5);
std::cout << score << '\n';
assert(score == 85);
}Output
85
Explanation
A reference parameter binds to the supplied object. Assignment through the reference updates that object, while a value parameter gives the function an independent copy.
Use a non-const reference for deliberate mutation. A const reference can avoid copying larger objects while preventing modification through that reference.
Explore the dry run
Guided walkthroughReady
1
#include <iostream>2
#include <cassert>3
void add_bonus(int& score, int bonus) {4
score += bonus;5
}6
int main() {7
int score = 80;8
add_bonus(score, 5);9
std::cout << score << '\n';10
assert(score == 85);11
}Follow the example
Start to inspect the source, values, and output. These prepared steps explain the published sample; grouped loop steps describe multiple iterations.
View the complete dry-run table
| Step / line | What happens | State after step | Output so far |
|---|---|---|---|
| Initialize the caller's value. | score = 80 | — | |
| Bind the reference and copy bonus. | reference -> caller score, bonus = 5 | — | |
| Update the referenced value. | caller score = 85 | — | |
| Print after the function returns. | caller score = 85 | 85 |
Cost and common mistakes
O(1) time and auxiliary space for bounded integers.
- A reference must not outlive the object it refers to.
- Mutation should be clear in a function's contract.
Try it yourself
Change the parameter to int score instead of int& score.
Reveal answer and reasoning
The caller would remain 80 because only a local copy changes; the existing assertion would fail.