9.2 — References: another name for the same box
Read one box at a time. No rush.
A second name tag#
A reference is a second name for an existing variable. Not a copy — the same box.
C++
int score { 10 };int& ref { score }; // ref is another name for score ref = 99;std::cout << score; // 99!int& reads as "reference to int".
Rules#
- A reference must be connected to something when it is made.
- It can never be switched to a different variable later.
C++ — wrong ✗
int& r; // error: a reference must refer to somethingconst references#
A const reference lets you look but not change:
C++
int lives { 3 };const int& view { lives }; std::cout << view; // fineview = 5; // error: it's const& (ampersand) has two jobs
In a type (int& r), & means reference. In front of a variable (&x), it means address of. Same symbol, different jobs.
Tip: press ← / → to move between lessons, / to search.