Use Assignment Operators in C++
An assignment operator in C++ is a binary operator that changes the value of its left argument. The equal sign (=), a simple assignment operator, is an absolute necessity in any programming language. This operator puts the value of the right-hand argument into the left-hand argument. The other assignment operators are odd enough that they seem to be someone’s whim.
So what about the following:
int var1; int var2 = 2; var1 = var2 = 1;
If you used the left to right rule, var1 ends up with the value 2 but var2 with the value 1, which is counterintuitive. To avoid this, multiple assignment operators are evaluated from right to left. Thus, the example snippet assigns the value 1 to var2 and then copies the same value into var1.
The creators of C (from which C++ originated) noticed that assignments often follow the form of
variable = variable # constant
where # is some binary operator. Thus, to increment an integer operator by 2, the programmer might write
nVariable = nVariable + 2;
This expression says, “Add 2 to the value of nVariable and store the results back into nVariable.” Doing so changes the value of nVariable to 2 more than it was.
Because the same variable appears on both sides of the = sign, the same Fathers of the C Revolution decided to create a version of the assignment operator with a binary operator attached. This says, in effect, “Thou shalt perform whatever operation on a variable and store the results right back into the same variable.”
Every binary operator has one of these nifty assignment versions. Thus, the assignment just given could have been written this way:
nVariable = nVariable + 2; nVariable += 2;
Here the first line says (being very explicit now), “Take the value of nVariable, add 2, and store the results back into nVariable.” The next line says (a bit more abruptly), “Add 2 to the value of nVariable.”
Other than assignment itself, these assignment operators are not used all that often. However, as odd as they might look, sometimes they can actually make the resulting program easier to read.