C assignment operators and increment (++) / decrement (--) explained.
= assigns, == compares+= -= *= /=++ adds 1, -- subtracts 1++i vs postfix i++= Does Not Mean "equals"a = b means "store the value of b into a". It's not the equals sign from math.int a, b; a = 5; // store 5 into a b = a + 3; // store (a+3)=8 into b a = a + 1; // store (a+1)=6 into a (a was 5, now it's 6)
a = a + 1 would be nonsense as an equation, but in C it means "take the current value of a, add 1, and store the result back into a" — so a simply goes up by 1.| Syntax | Meaning | Example | Result (when a=10) |
|---|---|---|---|
a += b | a = a + b | a += 3 | a = 13 |
a -= b | a = a - b | a -= 4 | a = 6 |
a *= b | a = a * b | a *= 2 | a = 20 |
a /= b | a = a / b | a /= 3 | a = 3 |
a %= b | a = a % b | a %= 3 | a = 1 |
sum += num; show up all over C, C++, Java, and Python.a grow. It builds intuition for the classic sum += i inside a loop.for (int i = 1; i <= n; i++) sum += i; just keeps adding i into sum. Tap the button a few times to get the feel.for loops.int i = 5; i++; // same as i = i + 1. i becomes 6 i--; // same as i = i - 1. i back to 5 ++i; // also i=i+1 (prefix form) for (int i = 0; i < 10; i++) { ... } // most common in for loops
i; then i increases by 1.i increases by 1 first; the expression's value is the new i.++i (prefix) and i++ (postfix) inside assignments and compare the resultsa += 3 and a *= 2int to a double and watch the automatic conversionCheck your understanding of this lesson!
a += 3 is equivalent to a = a + 3, so 5 + 3 = 8.
a++ is post-increment: the current value of a (5) is assigned to b first, and then a becomes 6.
++a is pre-increment: a becomes 6 first, and then that new value is assigned to b.