6

I came across the Order of evaluation page on cppreference and I can't undestand why these lines are considered undefined behavior.

i = ++i + 2;       // undefined behavior until C++11
f(i = -2, i = -2); // undefined behavior until C++17

In the first case, isn't the ++i assignment computed and then the sum and then the final assignment to i?

How about the second case? It seems to me that the function will get both arguments as -2 and the value of i will always be -2 after the execution.

dalmago
  • 106
  • 6
  • 8
    Before C++11, the rule was much simpler: a statement that modified a variable more than once had undefined behaviour. Both the statements you give do that, hence undefined behaviour. C++11 (and later standards) have changed the rules so a number of cases of behaviour that was previously undefined is now either unspecified or well-defined. In a number of cases (not all) I consider the changes to be dumb moves, since they often implicitly encourage writing more cryptic and hard-to-maintain code - but that's what quite a few people lobbied for. – Peter Jul 23 '19 at 12:01

0 Answers0