?: ternary conditional operator behaviour when leaving one expression empty

This is a GNU C extension (see ?: wikipedia entry), so for portability you should explicitly state the second operand.

In the ‘true’ case, it is returning the result of the conditional.

The following statements are almost equivalent:

a = x ?: y;
a = x ? x : y;

The only difference is in the first statement, x is always evaluated once, whereas in the second, x will be evaluated twice if it is true. So the only difference is when evaluating x has side effects.

Either way, I’d consider this a subtle use of the syntax… and if you have any empathy for those maintaining your code, you should explicitly state the operand. 🙂

On the other hand, it’s a nice little trick for a common use case.

Leave a Comment