TOPIC 1.6 · STUDY
Compound Assignment Operators
Compound assignment operators update a variable in place. +=, -=, *=, /=, and %= combine an arithmetic step with a store back into the left-hand variable. The standalone forms ++ and -- add or subtract one.
1.6.A
Compound assignment operators
A compound assignment names the variable once on the left, applies an operation with the right-hand value, and writes the result back into that same variable. The left side is both the source of the old value and the place the new value is stored.
The five compound forms you need are +=, -=, *=, /=, and %=. Each one matches a familiar arithmetic operator. Stick a value on the right, and the left-hand variable becomes the updated result.
| Operator | Meaning |
|---|---|
| += | Add the right side to the left variable and store the sum. |
| -= | Subtract the right side from the left variable and store the difference. |
| *= | Multiply the left variable by the right side and store the product. |
| /= | Divide the left variable by the right side and store the quotient. |
| %= | Divide and store the remainder, not the quotient. |
| ++ | Add 1 to the variable and store the result. |
| -- | Subtract 1 from the variable and store the result. |
int coins = 14;
coins += 9;
// coins is now 23
int chips = 11;
chips += chips;
// chips is now 22
int cloth = 23;
cloth %= 5;
// cloth is now 3 (remainder of 23 / 5)
int seat = 7;
seat++;
// seat is now 8
coins += 9 reads the stored 14, adds 9, and writes 23 back. chips += chips uses the current value on both sides, so it doubles chips. cloth %= 5 keeps the leftover after whole groups of 5 fit into 23. seat++ is the same idea as seat += 1, written as a standalone update.
The left box is the stored value before the statement. The right box is the same variable after += writes the new total.
When both sides are int, /= uses integer division: the fractional part is dropped before the result is stored. For example, int span = 20; span /= 6; leaves 3, not 3.333. The same rule applies to the quotient side of ordinary / between ints; %= is different because it stores the remainder instead.
int span = 20;
span /= 6;
// span is 3
int leftover = 20;
leftover %= 6;
// leftover is 2
Key points
- Each compound operator updates the variable written on the left.
- x += k means read x, add k, and store the sum back in x.
- x += x doubles x because the current value is used on both sides.
- ++ adds 1 and -- subtracts 1 as standalone updates.
- /= between ints stores the truncated quotient; %= stores the remainder.
Remember that %= keeps the remainder, not the quotient. After int ribbon = 23; ribbon %= 5;, ribbon holds 3 because 23 = 4 * 5 + 3. The matching /= would store 4.