Side effects, sequence points and undefined behavior

I read the following statement in the book:

n = ((i++) > (j)?(i++):(j)); 

The book claims that assuming that i> j, n has an unexpected value, and I doubled.
I do not understand why n has the expected value after this statement.
I read a lot of examples about undefined behavior, so here is my theory (and not an explanation of the book, as not) and tell me if I am correct:

at first, (i ++)> (j) is evaluated, and I may or may not be increased though.
Assuming i> n, (i ++) should be estimated. We do not know whether I have been enlarged or not , therefore, why all this statement is undefined. we are not sure whether I or I will refund +1.

Now the problem, suggesting that my theory is correct - Why do not we know I have still increased or have not been ? If this line of code were written as an if statement, I am sure that I will have to increase it earlier. So why is the connection if it is different?

Thanks.

+5
source share
1 answer

The ?: Operator introduces a sequence point, so there is no undefined behavior here.

(i++) > (j) , and the side effect of i++ is applied. If the result of (i++) > (j) is true, then (i++) is evaluated again, otherwise (j) is evaluated again.

i++ calculates the value of i before the increment. So, assuming i > j , after estimating

 n = i++ > j ? i++ : j; 

the following should be true:

 n = i orig + 1 i = i orig + 2 

Edit

Chapter and verse

6.5.15 Conditional statement
...
4 The first operand is evaluated; there is a point in the sequence between its evaluation and the evaluation of the second or third operand (depending on what is being evaluated). The second operand is evaluated only if the first is compared not equal to 0; the third operand is evaluated only if the first is compared to 0; the result is the value of the second or third operand (depending on what is being evaluated), is converted to the type described below. 110)
110) The conditional expression does not give an lvalue.
+5
source

Source: https://habr.com/ru/post/1233371/


All Articles