Conditional Operator

Top  Previous  Next

Operator:  ? :


condition ? expression1 : expression2


The expression condition is evaluated and converted to Boolean. If the result is true, then expression1 is evaluated; otherwise expression2 is evaluated. The result of the operator is the evaluated expression. Note that only one of the two possible result expressions is evaluated. There will be no side effects from the expression that is not evaluated.


This operator has right-to-left associativity. For example:


 condition ? expression1 : expression2 ? expression3 : expression4


is evaluated as:


 condition ? expression1 : (expression2 ? expression3 : expression4)


However, it is good programming practice to use parentheses whenever the conditional operator is nested to ensure the intended order of evaluation is clear.