Here is the code,
At the end, i is still 1 instead of 2,why? Thanks.Code:int i = 1;
i = i++;
Printable View
Here is the code,
At the end, i is still 1 instead of 2,why? Thanks.Code:int i = 1;
i = i++;
Undefined behavior... look up "sequence points"
http://en.wikipedia.org/wiki/Sequence_point
See 2nd paragraph.
I have a feeling it's defined in C++ 11. At least that's how I interpret section 5.2.6 in the standard: "The value computation of the ++ expression is sequenced before the modification of the operand object". In that case i = i++ is equivalent to this,
But it's still bad programming. If an outcome surprises you it probably surprises most programmers so it should be avoided.Code:int eval = i; // i++ is evaluated before incrementation
i++; // i is incremented
i = eval // the assignment is performed
I think that just establishes the "post-increment/decrement" aspect, i.e., the value of i++ is guaranteed to be the value of i since that is sequenced before the change to i. It does not mean that the increment operation is sequenced before the assignment operation in the code in post #1.Quote:
Originally Posted by nuzzle
In other words, I think that the wording would still allow a conforming compiler to translate it as if it were:
Code:int eval = i; // i++ is evaluated before incrementation
i = eval // the assignment is performed
i++; // i is incremented
Heh, thanks for the confirmation, but I just remembered: we still have a similiar rule in place, so the behaviour is not just implementation defined in C++11, but still undefined as in C++03:
Quote:
Originally Posted by C++11 Clause 1.9 Paragraph 15 (part)