Lesson 8 of 24

References and Pass by Reference

9 min 30 XP

A reference (int& r = x) is another name for a variable. Make a parameter a reference and the function can change the caller's variable without pointers. Use const& to pass big objects without copying them.

Example: edit me and press Run

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.

Pointer vs reference: a reference can't be null and can't be re-pointed to another variable. A popular interview question.

Challenge

+30 XP

Write void sortThree(int& a, int& b, int& c) that rearranges the three values into ascending order. In main(), read three numbers, call it and print them. Input: 9 2 5 → Output: 2 5 9

Output Loading C++ (first time takes a few seconds)
Press Run to see the result here.