TITLE: pre- vs post-increment

(Newsgroups: comp.lang.c++, 17 Mar 99)


PROCULUS: Claudius Proculus <x@xz.nl>

> For practical purposes, programmers should use the expression 
> that reads the clearest rather than attempt to outguess their 
> compiler.


KOENIG: Andrew Koenig <ark@research.att.com>

I mostly agree, even though I am about to make a statement that
looks at first like disagreement:

I believe that whenever you write an increment expression whose
explicit result is not used, you should use prefix ++ and --.

So, for example:

 for (int i = 0; i < n; ++i) { } // right

 for (int i = 0; i < n; i++) { } // wrong

The reason is that as far as its definition is concerned, i++
does everything that ++i does but has the extra side effect of
saving the original value of i and yielding it as its result.
That side effect is fine if you're going to use the resulting
value, but if you're not, you're just obscuring the meaning of
the program by asking for an unused side effect.

If i is an integer, the choice of prefix or postfix makes no
difference in practice, except for crummy compilers.  If, on
the other hand, i has a class type, such as an iterator, the
difference can be significant.

Of course, this whole rule goes out the window if i++ and ++i
are related in a different way from the normal one.

