Conditional-Expression Operator

C has one ternary operator: the conditional-expression operator (? :).      

Syntax

conditional-expression :

logical-OR-expression
logical-OR-expression ? expression : conditional-expression

The logical-OR-expression must have integral, floating, or pointer type. It is evaluated in terms of its equivalence to 0. A sequence point follows logical-OR-expression. Evaluation of the operands proceeds as follows:

Note that either expression or conditional-expression is evaluated, but not both.

The type of the result of a conditional operation depends on the type of the expression or conditional-expression operand, as follows:

In the type comparison for pointers, any type qualifiers (const or volatile) in the type to which the pointer points are insignificant, but the result type inherits the qualifiers from both components of the conditional.

Examples

The following examples show uses of the conditional operator:

j = ( i < 0 ) ? ( -i ) : ( i );

This example assigns the absolute value of i to j. If i is less than 0, -i is assigned to j. If i is greater than or equal to 0, i is assigned to j.

void f1( void );
void f2( void );
int x;
int y;
    .
    .
    .
( x == y ) ? ( f1() ) : ( f2() );

In this example, two functions, f1 and f2, and two variables, x and y, are declared. Later in the program, if the two variables have the same value, the function f1 is called. Otherwise, f2 is called.