Home Misc What is the difference between i++ and ++i ?

What is the difference between i++ and ++i ?

by nikoo28
0 comment 1 minutes read

Question:

In C, what is the difference between using ++i and i++, and which should be used in the incrementation block of a for loop ?

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.

You may also like

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More