Systems CourseC/C++ · Linux · Memory
C++ CoreLesson 04 of 441 min read6 questions

References

An alias to an existing variable, fixed at declaration.

Test yourself ↓

Concept core idea Watch out easy to get wrong

Concept

Key concepts

  1. A reference is an alias to an existing variable's address, fixed at declaration — cannot be reseated.
  2. Must be initialized when declared; cannot be null (in well-formed code); no reference arithmetic.
  3. Pass-by-value = copy (changes don't escape); pass-by-reference (int&) = writes go straight to the caller's variable.

Why pass by reference

Passing a big object by value copies it. A reference (or const reference) avoids the copy and can modify the caller's object.

C++
void addTip(int& bill){ bill += 10; }
void look(const std::string& s);  // no copy, read-only
Watch out

Easily confused

reference vs pointer
A reference is a fixed alias (no null, no reseating, no */&). A pointer can be null, reseated, and needs dereferencing.
pass-by-value vs pass-by-reference
By value copies the argument (changes stay local). By reference operates on the caller's actual variable.

Test yourself

6 questions on this lesson. Write your answers from memory, then compare them with the model answers side by side.