Friday, September 28, 2007

Why the postfix increment operator in for loops is a bad idea

The naive programmer writes:

for (i=0; i<100; i++)

to count from 0 to 99 while those who know better write

for (i=0; i<100; ++i)

There are two reasons for doing so. The first is on the grounds of efficiency: the postfix increment requires the creation of a temporary variable. Since the runtime value of i++ must different from i (i cannot be both values), the compiler will need to set aside space for a new variable and copy the original value of i to it.

Not only is it more efficient to use the prefix operator, but it is more elegant and semantically correct. The postfix increment says fetch me the value (which I don't have any need whatsoever for) of i and then when I'm done with it, then increment it; the prefix version simple says "increment the value of i."

It also translates better into proper English: ++i translates to "increment i" while i++ translates to the ungrammatical "i and increment" or the clumsy "evaluate i and then increment it."