Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is this multiple accesses to the same object between sequence points well-defined behavior?

Is this multiple access allowed?

#include <iostream>

int main()
{
    int A[1];
    A[0] = 0;
    A[A[0]] = 1;
    std::cout << A[0];
}

Refer to following paragraph...

Except where noted, the order of evaluation of operands of individual operators and subexpressions of individual expressions, and the order in which side effects take place, is unspecified. 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. The requirements of this paragraph shall be met for each allowable ordering of the subexpressions of a full expression; otherwise the behavior is undefined.

If this uses the old value of A[0] it should be undefined behavior, right?

like image 880
user4704019 Avatar asked Mar 23 '15 16:03

user4704019


1 Answers

Yes, it's valid.

First of all, reading A[0] on the LHS of the assignment is perfectly valid and well-defined for the same reason that this is:

int x = 42;
x = x + 1;

Both operands must be evaluated before the assignment can be executed.

Secondly, evaluating A[A[0]] in isolation is quite okay:

[C++11: 1.9/15]: [..] The value computations of the operands of an operator are sequenced before the value computation of the result of the operator. [..]

In C++03 the closest related wording I can find is the following regarding assignment (though there are examples of constructs such as a = a + x all over the gaff):

[C++03: 5.17/8]: If the value being stored in an object is accessed from another object that overlaps in any way the storage of the first object, then the overlap shall be exact and the two objects shall have the same type, otherwise the behavior is undefined.

like image 193
Lightness Races in Orbit Avatar answered Oct 04 '22 02:10

Lightness Races in Orbit