Archive - Originally posted on "The Horse's Mouth" - 2015-10-29 09:15:43 - Graham Ellis
In C, you can address a memory location storing a value directly by its variable name, or you can access it via its address using a variable that contains that address - a pointer - declared using an * in the declaration, and you can then use: *to mean contents of &to mean address of
in your code.
This works very well, but tends to become unwealdy and wordy, so C++ introduces a lighter weight way of aliasing a variable, known as a reference. You declare a refernce using & and it then becomes another name for the variable that it points at when it is defined - re-assign to it, and you're changing the contents of the variable being referenced, not which variable is being referenced.
The "trick", if you like to call it that, is that the alias is lost when the variable reference declaration goes out of scope - so that in his code for (int k=0; k<length; k++) {
int &valref = values[k];
cout << valref << endl;
valref += 12;
} valref is set as an alias in the second line, the value of the variable it's an alias for (a member of the values array) is changed in the fourth line - but it goes out of scope in the fifth line at the end of the loop and so it's freshly defined as a new alias to the next element of the array on the following time around the loop.