Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
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's evaluated in terms of its equivalence to 0. A sequence point follows logical-OR-expression. Evaluation of the operands proceeds as follows:
If
logical-OR-expressionisn't equal to 0,expressionis evaluated. The result of evaluating the expression is given by the nonterminalexpression. (It meansexpressionis evaluated only iflogical-OR-expressionis true.)If
logical-OR-expressionequals 0,conditional-expressionis evaluated. The result of the expression is the value ofconditional-expression. (It meansconditional-expressionis evaluated only iflogical-OR-expressionis false.)
The effect is, 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:
If
expressionorconditional-expressionhas integral or floating type (their types can be different), the operator performs the usual arithmetic conversions. The type of the result is the type of the operands after conversion.If both
expressionandconditional-expressionhave the same structure, union, or pointer type, the type of the result is the same structure, union, or pointer type.If both operands have type
void, the result has typevoid.If either operand is a pointer to an object of any type, and the other operand is a pointer to
void, the pointer to the object is converted to a pointer tovoidand the result is a pointer tovoid.If either
expressionorconditional-expressionis a pointer and the other operand is a constant expression with the value 0, the type of the result is the pointer type.
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.