C++ functions and references
Use a reference parameter to update a caller's value.
On this page
Functions and integer variables.
- Use a reference parameter to update a caller's value.
- Predict the sample output and explain the state changes.
- Complete the practice task and check the boundary cases.
The concept
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.
Code example
#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);
}85
Follow the code
Open the walkthrough to inspect the example one step at a time.
Show guided walkthrough
#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);}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 |
Behind the scenes
How C++ processes this code
The C++ compiler produces a native executable. Execution enters main, where objects and function calls perform the work.
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.