Assignment operators store a value in a writable object, such as an ordinary variable. The simple assignment operator is =.
Simple assignment
In total = 20;, the value 20 is stored in total. In total = a + b;, the right-hand expression is calculated first and its result is converted to the type of total for storage. The left side must be a valid destination; 20 = total; is invalid.
Compound assignment
+=: total += 5 adds 5 to total.
-=: total -= 5 subtracts 5.
*=: total *= 5 multiplies by 5.
/=: total /= 5 divides by 5 using the relevant arithmetic types.
%=: total %= 5 stores the integer remainder.
Bitwise forms: &=, |=, ^=, <<= and >>= combine a bit operation with assignment.
Worked example
Starting with int total = 10;, total += 5; gives 15. Next, total *= 2; gives 30. Finally, total -= 4; gives 26. For a simple variable, total += 5 has the usual effect of total = total + 5. A compound assignment evaluates its left operand only once.
Important points
= assigns; == compares. Assignment operators group from right to left: a = b = 0 stores zero in b and then a, when their types permit it. Do not divide by zero. Check whether a conversion loses a fraction or whether arithmetic exceeds the type range. A const-qualified object cannot be assigned a new value through that object.
Reference table
↔ Scroll horizontally on a small screen
Assignment forms
Form
Simple-variable explanation
x = y
Store the converted value of y in x.
x += y
Add y to x and store the result in x.
x -= y
Subtract y from x.
x *= y
Multiply x by y.
x /= y
Divide x by y, respecting the operand types.
x %= y
Store the integer remainder.
x &= mask
Apply bitwise AND and store the result.
x <<= count
Shift and store the result, subject to valid shift rules.
Key points
= assigns; == compares.
The stored result is converted to the destination type.