-1

I think, the assignment operators like =, +=... don't guarantee the order of evaluation of their operands, So It is usually Undefined Behavior to modify the same object in the same expression whose operator doesn't guarantee the order of evaluation of its operands.

  • My problem is why then I use this in my programs and in many examples:

    int x = 0;
    x = x + 1;
    

So is it UB in the assignment expression above?

Jesper Juhl
  • 30,449
  • 3
  • 47
  • 70
Itachi Uchiwa
  • 3,044
  • 12
  • 26
  • 7
    In `x = x + 1;` you are only modifying `x` once, so it can't be UB. – NathanOliver Aug 16 '19 at 20:02
  • 2
    related/dupe: https://stackoverflow.com/questions/4176328/undefined-behavior-and-sequence-points – NathanOliver Aug 16 '19 at 20:03
  • Imagine that this suddenly becomes true: now every single piece of software on planet Earth is freaking out because after `int x = 0; x = x + 1;` the variable `x` may very well become equal to `340` or whatever the heck it wants to. Stack Overflow is down, your bank balance is somewhere between -$1379 and $14649, nuclear missiles are roaming the airspace out of control... – ForceBru Aug 16 '19 at 20:08
  • 2
    `x + 1` does not modify x. – SergeyA Aug 16 '19 at 20:08
  • @SergeyA: So if it were: `x = x++` is UB? – Itachi Uchiwa Aug 16 '19 at 20:10
  • 2
    @ItachiUchiwa, no, because `=` introduces sequence point. See https://en.cppreference.com/w/cpp/language/eval_orderm, Rule 8. – SergeyA Aug 16 '19 at 20:18
  • @SergeyA I believe that's actually UB before C++17 because the rule you referenced only states that the side effect of the assignment is sequenced after the value computation of the right operand, not the side effect. This means that the side effect of post-increment is unsequenced relative to the side effect of the assignment. – eesiraed Aug 17 '19 at 00:35

1 Answers1

4

Contrary to what some other people have said here, a single side effect (modification) can result in UB if it's unsequenced relative to a value computation.

However, there's a rule that states "The side effect (modification of the left argument) of the built-in assignment operator and of all built-in compound assignment operators is sequenced after the value computation (but not the side effects) of both left and right arguments" (Source: cppreference.com) which is why x = x + 1 isn't UB.

eesiraed
  • 4,626
  • 4
  • 16
  • 34