I know that:
int b = 1, c = 2, d = 3, e = 4;
printf("%d %d %d", ++b, b, b++);
results in undefined behavior. Since
Modifying any object more than once between two sequence points is UB. Undefined behavior and sequence points
But I don't know if:
int b = 1, c = 2, d = 3, e = 4;
printf("%d", b++ + ++c - --d - e--);
is also UB?
What I think is that increment/decrement operators will evalute first because of the precedence, between them right to left since the associativity . Then arithmetic operators will be evaluated left to right.
Which will just be
(b) + (c + 1) - (d - 1) - (e)
that is, 1 + (2 + 1) - (3 - 1) - (4)
= (2 - 4)
= -2
Is it right?
There is a gigantic difference between the expressions
(which is fine), and
(which is rampantly undefined).
It's not using
++or--that makes an expression undefined. It's not even using++or--twice in the same expression. No, the problem is when you use++or--to modify a variable inside an expression, and you also try to use the value of that same variable elsewhere in the same expression, and without an intervening sequence point.Consider the simpler expression
Now, obviously the subexpression
++zwill incrementz. So the question is, does the+ zpart use the old or the new value of z? And the answer is that there is no answer, which is why this expression is undefined.Remember, expressions like
++zdo not just mean, "takez's value and add 1". They mean, "takez's value and add 1, and store the result back intoz". These expressions have side effects. And the side effects are at the root of the undefinedness issue.