-
June 4th, 2013, 07:48 PM
#1
Please help me understand the ouput.
Here is the code,
Code:
int i = 1;
i = i++;
At the end, i is still 1 instead of 2,why? Thanks.
-
June 4th, 2013, 07:56 PM
#2
Re: Please help me understand the ouput.
Undefined behavior... look up "sequence points"
http://en.wikipedia.org/wiki/Sequence_point
See 2nd paragraph.
-
June 5th, 2013, 12:10 AM
#3
Re: Please help me understand the ouput.
Originally Posted by Philip Nicoletti
Undefined behavior... look up "sequence points"
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,
Code:
int eval = i; // i++ is evaluated before incrementation
i++; // i is incremented
i = eval // the assignment is performed
But it's still bad programming. If an outcome surprises you it probably surprises most programmers so it should be avoided.
-
June 5th, 2013, 01:11 AM
#4
Re: Please help me understand the ouput.
Originally Posted by nuzzle
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".
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.
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
Last edited by laserlight; June 5th, 2013 at 01:15 AM.
-
June 5th, 2013, 01:34 AM
#5
Re: Please help me understand the ouput.
Originally Posted by laserlight
In other words, I think that the wording would still allow a conforming compiler to translate it as if it were:
Well, it looks like you're right. VS2012 actually outputs 2.
-
June 5th, 2013, 01:55 AM
#6
Re: Please help me understand the ouput.
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:
Originally Posted by C++11 Clause 1.9 Paragraph 15 (part)
If a side effect on a scalar object is unsequenced relative to either another side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|