Conditional operator ('? :')

Ternary operators

The conditional operator '?:' is, in fact, a ternary operator. It uses the following syntax:

expr1 ? expr2 : expr3
In the expression expr1 ? expr2 : Expr3, the operand expr1 must be of scalar type. The operands expr2 and Expr3 must obey one of the following sets of rules:
  1. Both of arithmetic type. In this case, both expr2 and Expr3 are subject to the usual arithmetic conversions, and the type of the result is the common type resulting from these conversions.
  2. Both of compatible structure or union types. In this case, the type of the result is the structure or union type of expr2 and expr3.
  3. Both of void type. In this case, the result is of type void.
  4. Both of type pointer to qualified or unqualified versions of compatible types. In this case, the type of the result is pointer to a type qualified with all the type qualifiers of the types pointed to by both operands.
  5. One operand of pointer type, the other a null pointer constant In this case, the type of the result is pointer to a type qualified with all the type qualifiers of the types pointed to by both operands.
  6. One operand of type pointer to an object, the other of type pointer to a qualified or unqualified version of void. In this case, the type of the result is that of the non-pointer-to-void operand.
In all cases, expr1 is evaluated first. If its value is nonzero (true), then expr2 is evaluated and expr3 is ignored (not evaluated at all). If expr1 evaluates to zero (false), then expr3 is evaluated and expr2 is ignored. The result of expr1 ? expr2 : expr3 will be the value of whichever of expr2 and expr3 is evaluated.

Note: GNU C extends the usage of the conditional operator to allow omitting the middle operand, so it may be used as a binary operator too.