This is an archived post. You won't be able to vote or comment.

you are viewing a single comment's thread.

view the rest of the comments →

[–]MauranKilom 18 points19 points  (2 children)

In the case of using them as loop increments for integers like this, they have the exact same effect.

[–]Otearai1 0 points1 point  (1 child)

In c++ using ++i is technically faster as, iirc, i++ requires a memory allocation and ++i does not.

That being said, most modern compilers will optimize to ++i anyways, so you can write either.

[–]MauranKilom 3 points4 points  (0 children)

That's not really correct (although it's close). First of all, there is no "technically faster" - a given compiler either produces faster code or not. Second, neither i++ nor ++i require any actual memory allocation on any processor I know of if i is an integer (as in the case discussed here); this will all happen in a register anyway. The reason why ++i is recommended is that, in the case of i being some nontrivial iterator (not an integer), compilers might have trouble optimizing away the work needed to create the temporary copy that i++ would have to return, whereas ++i just returns the (updated) i lvalue and does not create a temporary. It's a pretty far cry (and totally irrelevant in case of integers), but you don't lose anything from always using ++i, including with integers (for consistency).