Conditional Operator (?)

A conditional expressions is a compound expression that contains a condition (operand1), an expression to be evaluated if the condition has a non-zero value (operand2), and an expression to be evaluated if the condition has the value 0 (operand3).

Conditional expressions have right-to-left associativity. The left operand (operand1) is evaluated first, and then only one of the two remaining operands is evaluated. If that operand's expression contains or returns arithmetic types, the usual arithmetic conversions are performed on that expression's values.

The conditional expression contains one two-part operator. The ? symbol follows the condition, and the : appears between the two action expressions. All expressions that occur between the ? and : are treated as one expression.

The first operand must have a scalar type. The type of the second and third operands must be one of the following:

The second and third operands can also be a pointer or a null pointer constant.

Two object are compatible when they have the same type, but not necessarily the same type qualifiers (volatile or const). Pointer objects are compatible if they have the same type, or are pointers to void.

The first expression is evaluated first. If the first expression returns a non-zero value, the second expression is evaluated, converted to the result type, and becomes the value of the conditional expression. The third operand is ignored in this case. If the first expression instead returns a zero value, the third operand is evaluated, converted to the result type, and becomes the value of the conditional expression. The second expression is ignored in this case.

The types of the second and third operands determine the type of the result as shown below:

Type of One Operand Type of Other Operand Type of Result
Arithmetic Arithmetic Arithmetic type after usual arithmetic conversions
Structure or union type Compatible structure or union type Structure or union type with all the qualifiers on both operands
void void void
Pointer to compatible type Pointer to compatible type Pointer to type with all the qualifiers specified for the type
Pointer to type NULL pointer (the constant 0) Pointer to type
Pointer to object or incomplete type Pointer to void Pointer to void with all the qualifiers specified for the type

 



Operator Precedence and Associativity
Expressions and Operators
Types of Expressions


Operator Precedence and Associativity Table
Primary Operators
Unary Operators
Binary Operators
Assignment Operators
Comma Operator
Arithmetic Conversions
Pointer Arithmetic
void
Examples Using the Conditional Operator