Combining Dereference and Increment in a Single Expression
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 valuewhile (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 ...
Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.