Sequence points and side effects: Quiet change in C11?

前端 未结 4 1113
天涯浪人
天涯浪人 2020-12-31 06:42

C99 §6.5 Expressions

(1) An expression is a sequence of operators and operands that specifies computation of a value, or that designa

4条回答
  •  灰色年华
    2020-12-31 07:11

    This is an explanation of foo = ++i but not really an answer to the question.


    Prefix increment is defined in terms of compound assignment, see 6.5.3/2

    The expression ++E is equivalent to (E+=1)

    For assignment in general, there's a guarantee in 6.5.16/3

    The side effect of updating the stored value of the left operand is sequenced after the value computations of the left and right operands. The evaluations of the operands are unsequenced.

    So foo = ++i is equivalent to foo = (i+=1). The inner i+=1 requires the modification of i to be sequenced after the computation i+1. The resulting value of the expression (i+=1) is specified in 6.5.16/3 as:

    An assignment expression has the value of the left operand after the assignment, but is not an lvalue.

    It seems as if this requires the value computation of i+=1 to be sequenced after the modification of i, and in C++11, this is even guaranteed explicitly [expr.ass]/1

    In all cases, the assignment is sequenced after the value computation of the right and left operands, and before the value computation of the assignment expression.

    (which is clearer to me, but I know C++ far better than C)

    The modification of i is sequenced before the value computation of i+=1, so we don't have UB accessing the value of ++i in foo = ++i (as the value computation of the left and right operands of foo = x are sequenced before the modification of foo).

提交回复
热议问题