Conditional Operator


Syntax


 conditional_expression:
  logical_or_expression
  ? logical_or_expression expression conditional_expression

Notes

The conditional expression groups right to left. The first operand must be of arithmetic type and if it evaluates to non-zero then the returned value is that of the second operand, otherwise the returned value is that of the third operand. Side effects (if any) of the first expression take place prior to the evaluation of the second or third expression.

Example

The conditional operator is very useful for declaring and conditionally initializing an object in a single step. Where possible, it is 'good form' to initialize data when it is declared. To see how the conditional operator assists in this process, consider the following alternative ways of declaring and conditionally initializing a variable.

a = 1
b = 0

if a
 b = 10
else
 b = 20

c = ? a 10 20

Note that the variables b and c both acquired the value 10, however using the former technique, b had to be declared in an uninitialized state; whereas using the latter, c was declared and initialized in a single step.