Increment and Decrement
i++, i--, ++i, and --i.
4 minute read
Big idea
i++ adds 1 to i, and i-- subtracts 1. The position of the ++ decides whether you get the value before or after the change.
The idea
These all add 1 to count:
count = count + 1;
count += 1;
count++;
+= works with any number and any arithmetic operator: score += 10;, lives -= 1;, price *= 2;, n /= 10;.
Before or after?
On a line by itself, i++ and ++i do the same thing. The difference only shows when you use the value in the same expression:
i++(post-increment): use the old value, then add 1.++i(pre-increment): add 1 first, then use the new value.
#include <stdio.h>
int main(void) {
int a = 5;
int b = a++;
printf("a=%d b=%d\n", a, b);
int c = 5;
int d = ++c;
printf("c=%d d=%d\n", c, d);
return 0;
}What does it print? Show the answer
a=6 b=5
c=6 d=6Run and edit it in the app.
Step through the first half:
The rule that keeps you safe
Don't change a variable and read it again in the same expression — i = i++; or printf("%d %d", i++, i); are undefined behaviour: C doesn't promise any particular result, and different compilers really do give different answers. One ++ per variable per line.
Watch it
Think of it like
A ticket machine at a deli. ticket++ gives you the current number and then advances the counter. ++ticket advances the counter first and gives you the new number.
🕷️ Spidey-sense:
villains_caught++;— best line of code in the city. Pre or post, the count goes up either way.
Key terms
- Increment / decrement — Add 1 / subtract 1:
++/--. - Post-increment (
i++) — Gives the old value, then adds 1. - Pre-increment (
++i) — Adds 1, then gives the new value. - Compound assignment —
+=,-=,*=,/=,%=.
Check yourself
a = 5; b = a++; What is b?
a = 5; b = ++a; What is b?
Which is the same as x = x * 3;?