Assignment Operators and Expressions
A score that goes up in a game, a balance that changes with every transaction, and a countdown that ticks down by one each second. All of these share the same underlying operation: updating a variable based on what it holds already.
score = score + 2;balance = balance + 200;countdown = countdown - 1;C++ gives you a concise syntax 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 would 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. The assignment runs from right to left. We say it’s right-associative.
Chaining assignments is occasionally useful for initializing several counters or resetting a bunch of state at once.