Ad space (banner)
Lesson 10 / 20

References

This lesson covers references, a safer way than pointers to handle an "alias" for a variable. It's for anyone searching "C++ reference usage."

A reference gives an existing variable a second name. Declare one in the form type& variableName = originalVariable;, and unlike a pointer, you can treat it as if you're operating on the original variable directly, without writing * or & every time.

The example uses a reference, int& value, as a function parameter, so changing the value inside the function also affects the caller's variable.

A common early mistake is not seeing the difference from a pointer. A reference can't be re-bound to a different variable once linked, and it also can't have a "points to nothing" state like nullptr. That makes it usable more safely than a pointer.

In real projects, references are used a lot when passing large data to a function โ€” avoiding the cost of copying it, while still being able to modify the value.

๐Ÿ“– Reference code
โœ๏ธ Your code
Type your code, then press "Run"

๐Ÿงช This site can't compile or run C++ directly, so it checks on the spot whether what you typed matches the reference code (scoring happens entirely in your browser โ€” nothing is sent anywhere).

Ad space (banner)
Ad space (in-article)