The C standard (referring to C11
) does not mention anything about omitting the second operand. It specifies about all the three operands for the form
conditional-expression:
logical-OR-expression
logical-OR-expression ?
expression :
conditional-expression
You are talking about a compiler extension. The form
(exp1 ? : value2);
actually returns exp1
, if exp1
evaluates to TRUE.
Quoting the online documentation for gcc
,
The middle operand in a conditional expression may be omitted. [...]
Therefore, the expression
x ? : y
has the value of x
if that is nonzero; otherwise, the value of y
.
Just to add a bit of context in why or when this can be useful,
[...] When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.