Return Styles: Pseud0ch, Terminal, Valhalla, NES, Geocities, Blue Moon. Entire thread

i++ or ++i

Name: Anonymous 2011-09-11 21:20

I notice in for loops that the more experienced programmers will increment with ++i while the beginners use i++.

Is there every a reason to use one over the other or does it just give you a sense of superiority?

Name: Anonymous 2011-09-12 0:18

The compiler, regardless of whether it's C or C++, will optimize post-decrementation (i++) to pre-decrementation (++i) if the return value is not used IFF the type of i is integral (for example an int or a non-void pointer).

However, C++ iterators are often not integral or pointer types. They have their own over-ridden operator++ functions. If those operators are not inline functions, or if inlining is disabled in the case of debug-builds, the compiler can't make the above optimization. In which case, pre-increment on iterator variables is always faster because no temporary is created. This is why the experts, when programming in C++, choose to use pre-increment.

Using it here or there might seem as premature optimization, but it's one of those things that have no associated cost to the programmer to do, and when done consistently throughout your code-base can help make a small difference, especially in debug builds (nothing worse than trying to debug a program that is extremely fucking slow in debug mode).

Newer Posts
Don't change these.
Name: Email:
Entire Thread Thread List