References
Prerequisites: Variables and the auto keyword
A reference is an alias for an existing variable — unlike a
pointer, it can't be NULL, can't be reassigned to refer to
something else, and needs no * to use.
int x = 10;
int &ref = x; // ref IS x, just under another name
ref = 20;
std::cout << x << std::endl; // 20 — x itself changed
void increment(int &n) {
n++;
}
int main() {
int value = 5;
increment(value);
std::cout << value << std::endl; // 6
return 0;
}
This solves the exact same problem C used a pointer for
(increment(int *p)), with simpler syntax at the call site — no
&x needed when calling, and no *p needed inside the function.
Common mistakes
- Reaching for a pointer out of habit from C when a reference would be simpler and equally safe — use a reference whenever the argument can never legitimately be "no value at all."
Practice
Write a function void doubleIt(int &n) that doubles its
argument in place.
Show solution
void doubleIt(int &n) {
n *= 2;
}