Expressions with the Conditional Operator

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

  • The first operand is evaluated and all side effects are completed before continuing.
  • If the first operand evaluates to true (a nonzero value), the second operand is evaluated.
  • If the first operand evaluates to false (0), the third operand is evaluated.

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:

  • If both expressions are of the same type, the result is of that type.
  • If both expressions are of arithmetic types, usual arithmetic conversions (covered in Arithmetic Conversions in Chapter 3) are performed to convert them to a common type.
  • If both expressions are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type.
  • If both expressions are of reference types, reference conversions are performed to convert them to a common type.
  • If both expressions are of type void, the common type is type void.
  • If both expressions are of a given class type, the common type is that class type.

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.