Does 'a[i] = i;' always result in well defined behaviour?

后端 未结 6 1569
忘了有多久
忘了有多久 2021-02-05 11:19

There are several interesting questions raised here regarding undefined behaviour in C. One of them is (slightly modified)

Does the following piece of code r

6条回答
  •  耶瑟儿~
    2021-02-05 11:58

    This will result in undefined behavior in C++03, and well-defined behavior in C++11.

    C++03: Undefined Behvaior

    From the C++03 standard, section 5 paragraph 4:

    Between the previous and next sequence point a scalar object shall have its stored value modified at most once by the evaluation of an expression. Furthermore, the prior value shall be accessed only to determine the value to be stored.

    Note the second sentence: The previous value of i can only be used to determine the value to be stored. But here it is also used to determine the array index. So because this assignment will modify i, a[0] = i+1 is well defined, while a[i] = i+1 is not. Note that the assignment does not generate a sequence point: only the end of the full expression (the semicolon) does.


    C++11: Well defined behavior:

    C++11 got rid of the notion of sequence points, and instead defines which evaluations are sequenced before which.

    From the standard, section 1.9 paragraph 15:

    The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. 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.

    Both operands of the assignment operator are sequenced before the actual assignment. So both a[i] and i+1 will be evaluated, and only then will i be modified. The result is well defined.

提交回复
热议问题