Short circuit ternary operator in a certain way

If you have the following:

if (x) { y = *x; } else { y = 0; } 

Then the behavior is guaranteed, since we can only look for x if it is not 0

Is it possible to say the same:

 y = (x) ? *x : 0; 

This seems to work as expected (even compiled with -Wpedantic in g ++)

Is it guaranteed?

+5
source share
1 answer

Yes, only the second or third operand will be evaluated, the draft standard section of C ++ 5.16 [expr.cond] states:

Group conditional expressions from right to left. The first expression is contextually converted to bool (section 4). It is evaluated and, if true, the result of the conditional expression is the value of the second expression, otherwise the third expression. Only one of the second and third expressions is evaluated. Each calculation value and side effect associated with the first expression are sequenced before each value is calculated and the side effect associated with the second or third expression.

+12
source

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


All Articles