Both ++i and i++ add 1 to i. The difference is the value the expression gives back, which matters when we use it inside a larger expression:
- Pre-increment (
++i) changes the value first, then returns the new value. - Post-increment (
i++) returns the original value first, then changes the value.
Direct comparison
| Feature | Pre-increment (++i) |
Post-increment (i++) |
|---|---|---|
| Syntax | ++variable; |
variable++; |
| Order | Increments, then evaluates | Evaluates, then increments |
| Value returned | The updated value | The original value |
| Precedence | Lower (prefix) | Higher (postfix) |
1. In assignments
When we assign the result to another variable, the order decides the final values:
int a = 5;
int b = ++a; // 'a' becomes 6, then 6 is assigned to 'b'
printf("a = %d, b = %d\n", a, b);
int x = 5;
int y = x++; // 5 is assigned to 'y', then 'x' becomes 6
printf("x = %d, y = %d\n", x, y);Output:
a = 6, b = 6
x = 6, y = 5
2. Inside printf
The timing changes what appears on the screen:
int i = 10;
printf("%d\n", ++i); // increments first, prints 11
int j = 10;
printf("%d\n", j++); // prints the old value, 10
printf("%d\n", j); // now j is 11Output:
11
10
11
3. As a standalone statement
When the result is not used, there is no difference. i ends up as i + 1 either way. This is why a for loop works the same with i++ or ++i:
i++; // i becomes i + 1
++i; // i becomes i + 1Statements such as i = i++; or a[i] = i++; modify and read i without a defined order, so their behaviour is undefined in C. We keep ++ and -- to one use per variable in each expression.
Performance note
In C, a compiler produces the same code for a standalone ++i and i++. In C++, pre-increment is usually preferred for iterators and other objects, because post-increment must make a temporary copy of the old value. So ++i is a good habit to build early.
Summary
++i: update, then use the new value.i++: use the old value, then update.- On their own they are identical; the difference shows up only when the result is used.