Reputation: 9010
++i;
vs.
i++;
Does the use of prefix increment or the use of postfix increment make a difference in the given two statements (the point being that no other operation is involved there, except incrementing the variable)?
Upvotes: 0
Views: 230
Reputation: 1052
The end result is exactly the same in both scenarios. The use of ++i and i++ makes no difference in that regard. However, there may be performance differences; although, these would be almost absolutely negligible.
Basically, ++i is guaranteed to be as fast as i++; however, i++ is not guaranteed to be as fast as ++i. So, if you do not need the intermediate value [such as when ++i or i++ is a single statement], then prefer ++i. Most common compilers may optimize this difference out, but the specification is clear about the different behaviors and guarantees. In other words, i++ may do one additional unnecessary step.
// The compiler turns i++ into the following
int temp = i;
i = i + 1;
return temp;
Versus:
// The compiler turns ++i into the following
i = i + 1;
return i;
For a detailed reference about this, see http://fairwaytech.com/2012/03/prefix-vs-postfix-increment-and-decrement-operators-in-c/
Upvotes: 3