So why is the first version preferable? To answer that question, we will start by reviewing how normal variables work. Each regular variable is a name for a different location in memory (a different box to store things in). Given this code:
There are two storage locations, each with its own name. The second line of main make a new storage area with the name b and copies the value a has to it. When reading that code, you should picture a memory diagram that looks like this:
A reference changes this. A reference does not name its own storage, instead a reference always βpointsβ to some other storage. We declare a variable to be a reference by adding & to the data type, like int& b;. The & change the type of `b βit no longer is an βintβ, it is a βreference to an intβ.
When trying to pronounce complex looking data types in C++ it sometimes helps to read the backwards. int& b; can be read as βb is a reference to an integerβ.
b is an alias for a - it is another way to name the exact same storage that a names. If we change b, we change that value. Run this Codelens sample to see its animation of the situation:
The formal name in C++ for variables that name their own storage is an lvalue (location). A reference is an rvalue (reference). It is also possible to have an rvalue reference using the symbol &&.