Compund Operators and Assignment Expressions
You’ve already used = to store a value in a variable. The following examples do more than just assign. They update a variable based on its current value:
score = score + 2;balance = balance + 200;countdown = countdown - 1;C++ gives you a shorthand for exactly this pattern in the form of compound assignment operators.
Compound assignment operators
Each operator below performs the arithmetic operation and immediately stores the result back into the same variable:
What types can you use these with?
All the compound assignment operators work on numeric types: int, double, float, and their variants. The %= (modulo assignment) is the only exception, as one might expect. It only works on integer types, not floating-point.
Chaining assignments
C++ also lets you assign the same value to multiple variables in one line:
This works because in C++, assignment itself is an expression. In other words, once a variable is assigned a value, the entire expression takes on that value. So c = 0 evaluates to 0, then b = 0 evaluates to 0, then a = 0.
In particular, the evaluation follows how the chained assignment is grouped. The grouping starts from the right, so a = b = c = 0 is the same as a = (b = (c = 0)). That grouping is what we mean when we say the assignment operator is right-associative.