问题
Is this defined behaviour?
*p += *p--;
And, if it is, is it equivalent to { p[0] += p[0]; --p; }
or to { p[-1] = p[0]; --p; }
?
I'm guessing the being defined or not depends on whether +=
has an implicit sequence point and, if it has, my guess is that the second block should be the correct one.
EDIT: I think it's not a duplicate of the suggested question because the main question there is what are sequence points and how do the affect behaviour. In my case I have clear idea of what a sequence point is and the question is specifically on whether the +=
operator has an implicit sequence point or not.
回答1:
It is undefined behavior because the evaulation of *p
is unsequenced in related to the evaluation of *p--
. There is no sequence point. For all assignment operators, 6.5.16:
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.
6.5 states that it is UB:
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.
来源:https://stackoverflow.com/questions/30457904/c-operator-sequence-point