The short answer
++i and i++ both add 1 to the variable i. The difference is which value the expression gives back. ++i increments first and gives the new value. i++ gives back the old value and then increments.
Prefix and postfix
The prefix form, ++i, goes before the variable. The variable goes up by one, and the expression has the new value.
The postfix form, i++, goes after the variable. The expression has the value i held before the increment, and then i goes up by one.
This small program shows both forms:
#include <stdio.h>
int main(void) {
int a = 5;
int b = ++a; /* a becomes 6 first, then b gets 6 */
int c = a++; /* c gets 6 first, then a becomes 7 */
printf("a=%d b=%d c=%d\n", a, b, c); /* prints a=7 b=6 c=6 */
return 0;
}
When they do the same thing
On its own, ++i; and i++; do the same thing. The difference only shows up when the value is used. Many programmers write the prefix form in loops out of habit:
for (int i = 0; i < 3; ++i) {
/* runs three times */
}
Why ++i can matter more for classes
For a plain int, compilers usually produce the same machine code either way. For class types such as iterators, the postfix form has to keep a copy of the old object before it increments, so ++i may avoid that extra copy.
Avoid changing a variable twice in one expression
Expressions such as i = i++ + 1; change i more than once and are hard to read. In C, this has undefined behavior, so the result cannot be relied on. Put each change on its own line instead.
Unary operators in C
Both ++ and -- are unary operators in C, which means each one works on a single operand. --i and i-- follow the same rules as ++i and i++, except that they subtract 1.