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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With