| 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.
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 コイン + 今日初回完了時に小ボーナス付与
intによる除算は切り捨てられる:7/2 = 3。
x++は以下と同じ効果を持つ:...
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
x++は1を加えるので、x += 1と同じである。
複合演算子は長形式と同じ型ルールに従う(したがって、intに対する x /= 2 は切り捨てられる)。
難易度 1/5 · 100 コイン + 今日初回完了時に小ボーナス付与
略記法は計算内容を変えない — intによる除算は引き続き切り捨てられる。