On 12/14/2009 05:00 AM, Eric Sosman wrote:
> The value of the parenthesized sub-expression is the
> value of `i' after incrementation, yes. But where is it
> written that the sub-expression's value must be determined
> by actually reading it from `i'?
I don't think that's written--I think it can get the calculated value of
i++ from wherever it wants, but I think it is written that the side
effect of i++ (i.e. the modification of i) must occur before the
rightmost i is evaluated in the subexpression i,i++:
[C99 5.1.2.3p2]
# At certain specified points in the execution sequence called sequence
# points, all side effects of previous evaluations shall be complete and
# no side effects of subsequent evaluations shall have taken place.
[C99 6.5.1.7p2]
# The left operand of a comma operator is evaluated as a void
# expression; there is a sequence point after its evaluation.
I see how it's theoretically possible to perform this calculation:
i = (i, i++, i) + 1
without applying the side effect of storing i+1 in i, but I don't see
how it would be *legal* to do so under the Standard.
> If an optimizing compiler knew that `i' was 42 before the line in
> question, could it not replace the assignment with `i=44', with the
> `i++' happening at some undetermined moment?
In a world without sequence points, I'd totally allow i++ to store the
result in i at some undetermined moment, but the sequence point at the
comma forces the side effect to take place at that particular moment.
(Perhaps the side effect hasn't taken place in "machine code reality",
but it must have taken place in "C code reality".)
Of course, if an optimizing compiler can determine that none of the side
effects or calculations will be visible, it is free to optimize the
entire expression away (spelled out in C99 5.1.2.3p3). But I figure
that since we're discussing it, this particular optimization has not
occurred in this case.
-Beej