Expressions with the Conditional Operator

The conditional operator (? :) is a ternary operator (it takes three operands). The conditional operator works as follows:

The result of the conditional operator is the result of whichever operand is evaluated — the second or the third. Only one of the last two operands is evaluated in a conditional expression.

Syntax

conditional-expression :

logical-or-expression
logical-or-expression ? expression : conditional-expression

Conditional expressions have no associativity. The first operand must be of integral or pointer type. The following rules apply to the second and third expressions:

Any combinations of second and third operands not in the preceding list are illegal. The type of the result is the common type, and it is an l-value if both the second and third operands are of the same type and both are l-values.

For example:

(val >= 0) ? val : -val

If the condition is true, the expression evaluates to val. If not, the expression equals –val.