conditional_expression: logical_or_expression logical_or_expression ? expression : conditional_expression
The conditional expression groups right to left. The first operand must be of arithmetic or pointer 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. Of the second and third expressions, only one is capable of producing side effects - that being the one which is returned as the result.
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.
unsigned a = 1; unsigned b; if (a) b = 10; else b = 20; unsigned 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.
Conversions are performed (as required) to bring the second and third operands to the same type. These conversions, and the order in which they apply, are documented below.
If the second and third operands are of arithmetic type then they are converted according to the usual rules of arithmetic conversion. In this case, the returned result is of the type to which the operands are converted.