C assignment operators and increment (++) / decrement (--) explained.
= assigns, == compares+= -= *= /=++ adds 1, -- subtracts 1++i vs postfix i++= Does Not Mean "equal"a = b means "store the value of b into a". It is not the mathematical equals sign.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 6)
a = a + 1 makes no sense mathematically, but in C it means "take the current a, add 1, store it back into a", so the value increases 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; are common across C/C++/Java/Python.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 (prefix) and i++ (postfix) in assignments and watch the differencea += 3, a *= 2Check your understanding of this lesson!
a += 3 is equivalent to a = a + 3. So 5 + 3 = 8.
a++ is post-increment, so the current value of a (5) is assigned to b first, then a becomes 6.
++a is pre-increment, so a becomes 6 first, and then that value is assigned to b.
Learning the concepts here + doing exercises in a book is very effective
* These are affiliate links. Your purchases help support this site.