9.3 — Passing by reference
Read one box at a time. No rush.
Letting a function change things#
Remember: functions normally get a copy (6.3 — Inputs: parameters). With a reference parameter, they get the real variable.
C++▶ Run
void addBonus(int& points){ points += 50;} int main(){ int score { 100 }; addBonus(score); std::cout << score; // 150 return 0;}Swapping two values#
C++
void swapValues(int& a, int& b){ int temp { a }; a = b; b = temp;}(C++ has this built in as std::swap.)
Fast and safe: const reference#
Copying a big string or vector takes time. A const& parameter avoids the copy, and still promises not to change it:
C++
void printAll(const std::vector<std::string>& names){ for (const auto& n : names) std::cout << n << '\n';}Good habit
Pass small things (int, double, char, bool) by value. Pass big things (std::string, std::vector, your own structs) by const&. Use plain & only when the function needs to change the original.
Tip: press ← / → to move between lessons, / to search.