The conditional operator (?:) takes three operands. It tests the result of the first operand and then evaluates one of the other two operands based on the result of the first. Consider the following example:
E1 ? E2 : E3
If expression E1 is nonzero (true), then E2 is
evaluated, and that is the value of the conditional expression.
If E1 is 0 (false), E3 is evaluated, and that is
the value of the conditional expression. Conditional expressions
associate from right to left. In the following example, the
conditional operator is used to get the minimum of x
and y
:
a = (x < y) ? x : y; /* a = min(x, y) */
There is a sequence point after the first expression (E1). The following example's result is predictable, and is not subject to unplanned side effects:
i++ > j ? y[i] : x[i];
The conditional operator does not produce an lvalue. Therefore, a
statement such as a ? x : y = 10
is not valid.
The following restrictions apply:
void
.
void
. The result has the type
pointer to void
.