Possible Duplicate:
Is there a performance difference between i++ and ++i in C++?
In C++, I see people frequently use ++p in a for loop or elsewhere, where you want to increment a value, but not use the return value. I’ve heard this is more efficient because p++ returns the value before incrementing, and thus requires a temporary space.
But, it feels that even a very ignorant compiler will pull out that return value as dead code (as long as the increment code is inlined, and so the compiler can see that the return value wasn’t necessary).
I’m trying to come up with a good example where, using some sort of iterator, iter++ will actually create the copy (even though the return value of iter++ is not used.
After all, we don’t really frequently consider register allocation either when we write code with iterators.
I learned to use p++ simply because that’s what the book I learned from did. Is preferring ++p when no return value is used an archaic practice, or simply part of elegant coding? And why is the language not called ++C then?
p++is slower only when++pdoesn’t do the job – i.e. when you actually use the return value. Otherwise, the compiler will optimize the code to the same thing.People prefer using
++iinstead ofi++because it describes better what you intend to do: incrementi, more than incrementiand return the old value. Of course, you tend to stick to old habits. If you’re used to writingi++, that’s ok, unless the coding standards of the company you work for mandate you use++i.Sauce.