Compound Assignment Operators
| English | Chinese | Pinyin |
|---|---|---|
| compound assignment operator | 复合赋值运算符 | fù hé fù zhí yùn suàn fú |
Shorthand for updating
- Updating a variable from itself is so common it has shorthand.
- A compound assignment operator 复合赋值运算符 combines an operation with
=. x += 3;means exactlyx = x + 3;.- The family:
+=,-=,*=,/=,%=.
The five operators
x += 5→ add5tox.x -= 5→ subtract5.x *= 2→ doublex.x /= 2→ halvex(int rules apply).x %= 3→ replacexwithx % 3(the remainder).- Each reads the current value, applies the op, and stores the result back.
Increment and decrement
x++adds1tox(same asx += 1orx = x + 1).x--subtracts1fromx.- These are extremely common in loops to step a counter.
- They change the variable in place — no
=needed.
Same type rules apply
- Compound operators obey the same type rules as the long form.
int x = 7; x /= 2;gives3(int division still truncates).x += 2.5;on anintwould need care — the type ofxdoesn't change.- The shorthand is only shorter; the arithmetic is identical.
x += 3 is exactly x = x + 3 — the type rules don't change. So int x = 7; x /= 2; still gives 3 (int division truncates), not 3.5. Compound operators are pure shorthand; if the long form would truncate or overflow, so does the short form. And x++ is just x += 1.
Tracing a counter:
int x = 10;x += 5;→xis15.x *= 2;→xis30.x--;→xis29.x %= 5;→xis4(29 % 5).
Compound assignment operators (+=, -=, *=, /=, %=) are shorthand: x += 3 means x = x + 3. x++ and x-- add or subtract 1. They obey the same type rules as the long form — int division in x /= 2 still truncates.
Stepping a counter
Each compound operator updates x in place.
x += 3 is exactly the same as...
Compound assignment is shorthand for x = x + 3.
int x = 10; x += 5; x *= 2; What is x?
10 → 15 → 30.
int x = 7; x /= 2; What is x?
int division truncates: 7/2 = 3.
x++ has the same effect as...
x++ adds 1, same as x += 1.
Compound operators follow the same type rules as the long form (so x /= 2 on an int truncates).
Shorthand doesn't change the arithmetic — int division still truncates.