7.12 Conditional operator
The ?: operator is called the conditional operator. It is at times also called the ternary operator.
- conditional-expression:
- conditional-or-expression
conditional-or-expression ? expression : expression
A conditional expression of the form b ? x : y first evaluates the condition b. Then, if b is true, x is evaluated and becomes the result of the operation. Otherwise, y is evaluated and becomes the result of the operation. A conditional expression never evaluates both x and y.
The conditional operator is right-associative, meaning that operations are grouped from right to left. For example, an expression of the form a ? b : c ? d : e is evaluated as a ? b : (c ? d : e).
The first operand of the ?: operator must be an expression of a type that can be implicitly converted to bool, or an expression of a type that implements operator true. If neither requirement is satisfied, a compile-time error occurs.
The second and third operands of the ?: operator control the type of the conditional expression. Let X and Y be the types of the second and third operands. Then,
- If
XandYare the same type, then this is the type of the conditional expression. - Otherwise, if an implicit conversion (Section 6.1) exists from
XtoY, but not fromYtoX, thenYis the type of the conditional expression. - Otherwise, if an implicit conversion (Section 6.1) exists from
YtoX, but not fromXtoY, thenXis the type of the conditional expression. - Otherwise, no expression type can be determined, and a compile-time error occurs.
The run-time processing of a conditional expression of the form b ? x : y consists of the following steps:
- First,
bis evaluated, and theboolvalue ofbis determined:- If an implicit conversion from the type of
btoboolexists, then this implicit conversion is performed to produce aboolvalue. - Otherwise, the
operatortruedefined by the type ofbis invoked to produce aboolvalue.
- If an implicit conversion from the type of
- If the
boolvalue produced by the step above istrue, thenxis evaluated and converted to the type of the conditional expression, and this becomes the result of the conditional expression. - Otherwise,
yis evaluated and converted to the type of the conditional expression, and this becomes the result of the conditional expression.