What is the difference between ++i and i++?
Short answer: ++i (pre-increment) increments i and gives the new value. i++ (post-increment) gives the old value, and i is incremented as a side effect. Used alone as a statement, for example in a for loop, they generate identical code for integers; the difference only matters when the result is used.
int i = 5;
int a = ++i; /* i = 6, a = 6 */
int b = i++; /* b = 6, i = 7 */
while (n--) { } /* tests the old value: runs n times */
while (--n) { } /* tests the new value: runs n - 1 times */
Common uses of post-increment
buf[len++] = byte; /* store at len, then advance */
*dst++ = *src++; /* copy one element, advance both pointers */
*p++ means *(p++): increment the pointer, return the old pointed value. (*p)++ increments the value.
Performance: for built-in types any modern compiler produces the same code. In C++, for class types such as iterators, i++ has to make a copy of the old value, so ++i is preferred out of habit.
Undefined behaviour reminder: do not use the same variable twice in an expression that increments it: a[i] = i++; and i = i++; are undefined.
Interview puzzle: what does this print?
int x = 5;
printf("%d %d\n", x++, x); /* undefined: x is read and modified unsequenced */
The correct answer is "it is undefined"; any specific output is a guess about a particular compiler.