The postfix versions of ++
and --
are used when we want to use the current value of a variable and increment it in a single compound expression.
As one example, we can use postfix increment to write a loop to print the values in a vector
up to but not including the first negative value:
auto pbeg = v.begin();
// print elements up to the first negative value
while (pbeg != v.end() && *beg >= 0)
cout << *pbeg++ << endl; // print the current value and advance pbeg
The expression *pbeg++
is usually confusing to programmers new to both C++ and C. However, because this usage pattern is so common, C++ programmers must understand such expressions.
The precedence of postfix increment is higher than that of the dereference operator, so *pbeg++
is equivalent to *(pbeg++)
. The subexpression pbeg++
increments pbeg
and yields a copy of the previous value of pbeg
as its result. Accordingly, the operand of *
is the unincremented value of pbeg
. Thus, the statement prints the element to which pbeg
originally pointed and increments pbeg
.
This usage relies on the fact that postfix increment returns a copy of its original, unincremented operand. If it returned the incremented value, we’d dereference the incremented value, with disastrous results. We’d skip the first element. Worse, if the sequence had no negative values, we would attempt to dereference one too many elements.
Advice: Brevity Can Be a Virtue
Expressions such as *pbeg++
can be bewildering—at first. However, it is a useful and widely used idiom. Once the notation is familiar, writing
cout << *iter++ << endl;
is easier and less error-prone than the more verbose equivalent
cout << *iter << endl;
++iter;
It is worthwhile to study examples of such code until their meanings are immediately clear. Most C++ programs use succinct expressions rather than more verbose equivalents. Therefore, C++ programmers must be comfortable with such usages. Moreover, once these expressions are familiar, you will find them less error-prone.
3.145.125.51