Ternary Operator ?:
Syntax
expression1 ? expression2 : expression3Description
Evaluatesexpression1 (must result in a bool type). If expression1 is true, expression2 is executed and its value is returned. If expression1 is false, expression3 is executed and its value is returned. expression2 and expression3 must return values of the same type and cannot be of void type.Operator Use Restrictions
NULL can be used for pointers.
* If types are simple, the operator result type is the maximum of the two types.
* If one value is an enumeration and the other is numeric, the enumeration is cast to int, and the maximum type rule applies.
* If both values are enumerations, they must be of identical types, and the operator result type is that enumeration type.
NULL can be used for pointers.Type Determination for Overloaded Functions
The type of the ternary operator's result is determined at compile time as the larger of the types of expression2 and expression3. This can lead to implicit casting when used as an argument for overloaded functions.
Example
// normalize difference between open and close prices for a day range
double true_range = (High==Low)?0:(Close-Open)/(High-Low);// Equivalent if-else structure:
double true_range;
if(High==Low) true_range=0;
else true_range=(Close-Open)/(High-Low);
See Also
Previous
arrow_back
If else operator