< Previous | Contents | Next >
Next I increase the value of myScore by 500.
myScore += 500;
When I send myScore to cout, 1500 is displayed, just as you’d expect. When I send mikesScore to cout, 1500 is also displayed. Again, that’s because mikesScore is just another name for the variable myScore. In essence, I’m sending the same variable to cout both times.
Next I increase mikesScore by 500.
mikesScore += 500;
Because mikesScore is just another name for myScore, the preceding line of code increases the value of myScore by 500. So when I next send myScore to cout, 2000 is displayed. When I send mikesScore to cout, 2000 is displayed again.
Passing References to Alter Arguments 191
Tra p
A reference always refers to the variable with which it was initialized. You can’t reassign a reference to refer to another variable so, for example, the results of the following code might not be obvious.
int myScore = 1000;
int& mikesScore = myScore; int larrysScore = 2500;
mikesScore = larrysScore; //may not do what you think!
The line mikesScore = larrysScore; does not reassign the reference mikesScore so it refers to larrysScore because a reference can’t be reassigned. However, because mikesScore is just another name for myScore, the code mikesScore = larrysScore; is equivalent to myScore = larrysScore;, which assigns 2500 to myScore. And after all is said and done, myScore becomes 2500 and mikesScore still refers to myScore.