In C, what is the difference between using
i++, and which should be used in the incrementation block of a for
i++ is known as Post Increment whereas ++i is called Pre Increment.
++i will increment the value of i, and then return the incremented value.
int i = 1; int j = ++i; printf("i is = %d", i); // i is = 2 printf("j is = %d", j); // j is = 2
i++ will increment the value of i, but return the original value that i held before being incremented.
int i = 1; int j = i++; printf("i is = %d", i); // i is = 2 printf("j is = %d", j); // j is = 1
For a for loop, either works. ++i seems more common, perhaps because that is what is used in Dennis Ritchie.
In any case, follow the guideline “prefer ++i over i++” and you won’t go wrong.