Both cases are related to some kind of undefined behavior, because you increase a by returning a and assigning a on the left side within two points of the sequence. 3 is required for a well-defined result.
In this case: a = (a < b) ? a++ : b++; a = (a < b) ? a++ : b++;
- if
a less than b a returned (value = 5) as a result of the ternary operatora increases (value = 6).- the result of ternary operator (5) is assigned to the left side of the variable
a (rewriting 6)
The order of steps 3 and 4 is not defined. This is equivalent to a = a++;
In this case: a = (a++ < b++) ? a : b; a = (a++ < b++) ? a : b;
- If
a less than b a and b increase (no matter which is smaller)a returns as a result of the triple operator- assigned to the left side the variable
a
The order of steps 2 and 3 is not clearly defined.
It is important to keep track of sequence points in such cases. Relevant Rules:
- The first expression of the ternary operator to the left of
? sequenced before the second or third expression. And any of them is sequenced before the appointment. ? comparison sequenced before ?- In expressions such as
a++ , the value is returned before the increment
Undefined behavior:
- In expressions like
a = a++; there is no sequence point between the (post) increment a and the destination a on the left side. Both options are executed after returning the initial value a - In expressions like
a++ ? a : b a++ ? a : b there is no sequence point between the (post) increment of a and the return of a from the ternary operator. Both occur after ?
source share