简体   繁体   中英

Side effects, sequence points and undefined behaviour

I read in a book the following statement:

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

The book claims that presuming i >j, n has an unexpected value and i is incremented twice.
I don't understand why n has an expected value after this statement.
I read many examples about undefined behavior, so here's my theory (not the book's explanation, since there isn't) and tell me whether I'm right:

first, (i++) > (j) is evaluated, and i may or may not be incremented yet.
Presuming i > n, (i++) should be evaluated. We don't know whether i has been incremented yet or not , so that's why this entire statement is undefined. we're not sure whether i or i+1 will be returned.

Now here's the problem presuming my theory is right - Why don't we know whether i has been incremented yet or not ? If this line of code were to be written as an if statement, I'm pretty sure i will have to be incremented before. So why is the compound if different?

Thank you.

The ?: operator introduces a sequence point, so there's no undefined behavior here.

(i++) > (j) is evaluated 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++ evalutes to the value of i before the increment. So, assuming i > j , then after evaluating

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

the following should be true:

n = iorig + 1
i = iorig + 2

Edit

Chapter and verse

6.5.15 Conditional operator
...
4 The first operand is evaluated; there is a sequence point between its evaluation and the evaluation of the second or third operand (whichever is evaluated). The second operand is evaluated only if the first compares unequal to 0; the third operand is evaluated only if the first compares equal to 0; the result is the value of the second or third operand (whichever is evaluated), converted to the type described below. 110)
110) A conditional expression does not yield an lvalue.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM