Toán tử gán tổng hợp
Đã giới thiệu| English | Ý nghĩa |
|---|---|
| compound assignment operator/ˈkɒmpaʊnd əˈsaɪnmənt ˈɒpəreɪtə/ | toán tử gán phức hợp |
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.
Tăng bộ đếm
Mỗi toán tử tổng hợp cập nhật x ngay tại chỗ.
x += 3 hoàn toàn giống với...
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
Gán tổng hợp là viết tắt của x = x + 3.
int x = 10; x += 5; x *= 2; Giá trị của x là gì?
Độ khó 2/5 · 140 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
10 → 15 → 30.
int x = 7; x /= 2; Giá trị của x là gì?
Độ khó 2/5 · 140 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
Phép chia int bị làm tròn: 7/2 = 3.
x++ có cùng tác dụng như...
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
x++ cộng thêm 1, giống hệt x += 1.
Các toán tử tổng hợp tuân theo các quy tắc kiểu dữ liệu giống như dạng đầy đủ (vì vậy x /= 2 trên biến int sẽ bị làm tròn).
Độ khó 1/5 · 100 xu + một phần thưởng nhỏ cho lần hoàn thành đầu tiên trong ngày
Dạng viết tắt không thay đổi phép toán — phép chia int vẫn bị làm tròn.