"C++ Primer" (5th edition) on page 148 defines the postfix increment operator: "The postfix operator returns a copy of the object's original value as an rvalue." This made sense to me. However, on page 149, it brings the following code as an example of undefined behavior:
while (beg != s.end() && !isspace(*beg))
*beg = toupper(*beg++);
It proceeds to explain that, if the right side of the assignment is evaluated before the left side, then the compiler would evaluate the above expression as:
*(beg+1) = toupper(*beg)
To me this contradicts the above definition of the postfix increment operator. Namely, =
is just an operator, so the whole line *beg = toupper(*beg++)
is an expression, so that the effects of incremented value of beg
should be held and not take any effect before the expression is fully evaluated. So, what is the precise definition of when the postfix increment takes effect? Also, does placing parentheses in the expression affect when this happens?
A similar question appeared at: Does postfix increment perform increment not on returned value?. One of the comments there cited the following discussion about sequence points: Undefined behavior and sequence points. However, I believe that there should be a short and clear definition: when does the postfix increment take effect? Without such a definition, I would be afraid to use the postfix form in any expression that's more complicated than the standard *p++
with no other uses of p
in the expression.