Can someone please explain whether i = x[i]++;
lead to undefined behavior?
Note: x[i]
and i
are not both volatile and x[i]
does not overlap i
.
There is C11, 6.5 Expressions, 2 (emphasis added):
If a side effect on a scalar object is unsequenced relative to either a different side effect on the same scalar object or a value computation using the value of the same scalar object, the behavior is undefined. If there are multiple allowable orderings of the subexpressions of an expression, the behavior is undefined if such an unsequenced side effect occurs in any of the orderings. 84)
As I understand:
- there is no "different side effect on the same scalar object"
- there is no "value computation using the value of the same scalar object"
Are there "multiple allowable orderings"?
Overall: how can the i = x[i]++;
be interpreted w.r.t. sequence points, side effects, and undefined behavior (if any)?
UPD. Conclusion: the i = x[i]++;
leads to 2 side effects:
- "the value of the operand object is incremented" (Postfix increment)
- "updating the stored value of the left operand" (Assignment operators)
The Standard does not define the order in which the side effects take place.
Hence, per C11, 4. Conformance, 2:
Undefined behavior is otherwise indicated in this International Standard by the words ‘‘undefined behavior’’ or by the omission of any explicit definition of behavior.
Experiments show that GCC/LLVM/ICC have order 1-2
, while MSVC (and some others) have order 2-1
.
Extra (speculating): why not making it unspecified behavior? Example: "an example of unspecified behavior is the order in which the side effects take place"?
i = x[i]++;
what is the order of the following side effects: "the value of the operand object is incremented" (Postfix increment) and "updating the stored value of the left operand" (Assignment operators)? Can this order (if any) be deduced? – Wesla