I came across a set of slides for a rant talk on C++. There were some interesting tidbits here and there, but slide 8 stood out to me. Its contents were, approximately:
Ever-changing styles
Old and busted:
for (int i = 0; i < n; i++)
New hotness:
for (int i(0); i != n; ++i)
I'd never seen a for
loop using the second form before, so the claim that it was the "New hotness" interested me. I can see some rationale for it:
- Direct initialization using a constructor vs copy initialization
!=
could be faster in hardware than<
++i
doesn't require the compiler to keep the old value ofi
around, which is whati++
would do.
I'd imagine that this is premature optimization, though, as modern optimizing compilers would compile the two down to the same instructions; if anything, the latter is worse because it isn't a "normal" for
loop. Using !=
instead of <
is also suspicious to me, because it makes the loop semantically different than the original version, and can lead to some rare, but interesting, bugs.
Was there any point where the "New hotness" version of the for
loop was popular? Is there any reason to use that version these days (2016+), e.g. unusual loop variable types?
++i
is better thani++
not for any arcane reasons of second-guessing the compiler, but because it's what you mean. Write code that does what you mean, not some other code that happens to solve your problem as a side effect. But that's been true since 1972, so I wouldn't call that "new hotness".<
when the ordering of integers is material to the algorithm. Otherwise, if all you want is a sentinel that signals the end of the iteration, then!=
is more appropriate, since it makes fewer assumptions about the details and concentrates on the underlying logic. The benefit is that the very thought process is now "portable", since it applies to a much more general concept of iteration. Again, the technicalities haven't changed since 1972, but the experience with generality and code reuse has.