NOTE: This document may be circulated or quoted from freely, as long as the copyright credit is included.
The operator-rich C programming language provided increment
(++) and decrement
(--) operators in two forms:
++k)
k++)
C's descendants, C++, Java, and C#, support those operators.1
That allows compact expressions, often avoiding the need for multiple
assignment statements and temporary variables. When
one of these operators appears within a longer expression, for example as an array subscript,
it makes a huge difference whether the prefix or the postfix form was used. However, these
operators are also sometimes used in a complete statement, especially as the increment
specification in a for statement.
for (ctr=0; ctr<N; ++ctr)
In that case it makes no difference at all to the result whether the prefix or postfix form was specified. But it can make a significant difference in the program's performance.
If the operand is a built-in type, such as int,
then the two are equivalent, but if the operand is an instance of a class, such as a
Date object or an iterator, then the
overloaded postfix operator has to create a new temporary
object2, which
may involve memory allocation or other expensive overhead. On the other hand an overloaded
prefix operator just advances the value of the operand object and returns that
object.
But for reasons that I've never heard explained many, perhaps most, textbooks3 and course materials have adopted the opposite convention:
for (ctr=0; ctr<N; ctr++) // No!
and that pattern has influenced the coding of thousands of programmers who churn it
out almost automatically. While some may argue that it makes no difference (because
they use the increment operator only with built-in types), I find the practice
puzzling. If it makes no difference, why not cultivate the habit of the more direct
and efficient option? Future program maintenance might replace a simple
int with an
object, and even Java may eventually accept overloaded operators.
2—so that it can return the old value.
3—One book that gets it right, not surprisingly, is Scott Meyers's More Effecive C++, which advises that programmers should "prefer prefix increment to postfix increment, unless they really need the behavior of postfix increment." -item #6.
Return to IDI Home Page
Return to Technical articles
Last modified October 7, 2008