Ternary Operator ?:

Syntax

expression1 ? expression2 : expression3

Description

Evaluates expression1 (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

  • **General:**
  • * Do not mix user-defined types with simple or enumeration types. 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.
  • **User-Defined Types (Classes/Structs):**
  • * Types must be identical or one derived from the other. * If types are not identical (inheritance), the child is implicitly cast to the parent type, and the operator result type is the parent type. * Do not mix objects and pointers; both must be objects or pointers. 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

  • [Conditional Operator if-else](/basis/operators/if)
  • [Switch Operator](/basis/operators/switch)
  • [Initialization of Variables](/basis/variables/initialization)
  • [Visibility Scope and Lifetime of Variables](/basis/variables/variable_scope)
  • [Creating and Deleting Objects](/basis/variables/object_live)