Operator Penugasan Majemuk
Diperkenalkan| English | Makna |
|---|---|
| compound assignment operator/ˈkɒmpaʊnd əˈsaɪnmənt ˈɒpəreɪtə/ | operator penugasan majemuk |
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.
Menambah nilai counter
Setiap operator majemuk memperbarui x secara in-place.
x += 3 sama persis dengan...
Kesulitan 1/5 · 100 koin + bonus kecil pada penyelesaian pertama hari ini
Penugasan majemuk adalah singkatan dari x = x + 3.
int x = 10; x += 5; x *= 2; Berapakah nilai x?
Kesulitan 2/5 · 140 koin + bonus kecil pada penyelesaian pertama hari ini
10 → 15 → 30.
int x = 7; x /= 2; Berapakah nilai x?
Kesulitan 2/5 · 140 koin + bonus kecil pada penyelesaian pertama hari ini
Pembagian int memotong: 7/2 = 3.
x++ memiliki efek yang sama dengan...
Kesulitan 1/5 · 100 koin + bonus kecil pada penyelesaian pertama hari ini
x++ menambah 1, sama dengan x += 1.
Operator majemuk mengikuti aturan tipe yang sama dengan bentuk panjang (sehingga x /= 2 pada int akan memotong).
Kesulitan 1/5 · 100 koin + bonus kecil pada penyelesaian pertama hari ini
Bentuk singkat tidak mengubah aritmatika — pembagian int tetap memotong.