It is perfectly legal C++ to make more than one assignment to the same variable. The effect of the second assignment is to replace the old value of the variable with a new value. (This is why they are called βvariablesββthey can vary!)
To picture this kind of multiple assignment you can think of a variable as the name of a container for values. When you assign a value to a variable, you change the contents of the container with that name, as shown in the figure:
Using one variable to assign the value of another copies the value of the first variable into the second variable. This means that after the assignment, there are two copies of the same value. But the variables that hold those values are independent. Changing one will not change the other:
In mathematics, a statement of equality is true for all time. If \(a = b\) now, then \(a\) will always equal \(b\text{.}\) In C++, an assignment statement canβt permanently make two variables equal. All it can do it copy the current value from one variable to another.
Although multiple assignment is frequently useful, you should use it with caution. If the values of variables are changing constantly in different parts of the program, it can make the code difficult to read and debug. You generally should only use it when the same conceptual value changes. If you are programming a game, using multiple assignment to change the score variable every time the player scores points would make sense. But using multiple assignment to reuse variables for different purposes is generally a bad idea. Having a variable length that initially stores a value in inches and later is changed to store a value in centimeters would cause confusion for anyone trying to read the code.