Составные операторы присваивания
Введено| English | Значение |
|---|---|
| compound assignment operator/ˈkɒmpaʊnd əˈsaɪnmənt ˈɒpəreɪtə/ | оператор сложного присваивания |
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.

Compound assignment operators traced on one variable
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.
Инкремент счетчика
Каждый составной оператор обновляет x на месте.
x += 3 это то же самое, что...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Составное присваивание — это сокращенная запись для x = x + 3.
int x = 10; x += 5; x *= 2; Каково значение x?
Сложность 2/5 · 140 монет + небольшой бонус за первое выполнение сегодня
10 → 15 → 30.
int x = 7; x /= 2; Каково значение x?
Сложность 2/5 · 140 монет + небольшой бонус за первое выполнение сегодня
Целочисленное деление отбрасывает дробную часть: 7/2 = 3.
x++ имеет тот же эффект, что и...
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
x++ добавляет 1, то же самое, что x += 1.
Составные операторы подчиняются тем же правилам типов, что и полная форма (поэтому x /= 2 для int отбрасывает дробную часть).
Сложность 1/5 · 100 монет + небольшой бонус за первое выполнение сегодня
Сокращенная форма не меняет арифметику — целочисленное деление все равно отбрасывает дробную часть.