0

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.

  • possible duplicate of [Undefined behavior and sequence points](http://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points) – BlackDwarf May 26 '15 at 12:04
  • I had not seen the question when I posted this one, but Lundin's answer is definitely more clarifying to me that the answers to the question you mention. – Toni Homedes i Saun May 26 '15 at 12:24

1 Answers1

3

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.

Lundin
  • 195,001
  • 40
  • 254
  • 396