Solace
Solace

Reputation: 9010

Prefix vs. Postfix increment when no other operation is involved?

++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

Answers (2)

Kevin Carrasco
Kevin Carrasco

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

tagh
tagh

Reputation: 1037

No. It just increment the value of i by one and that's it.

Upvotes: 1

Related Questions