The Conditional (?:) Ternary Operator

  1. C++ has a conditional expression of the form:

    condition ? expression1 : expression2

    where "condition" is a boolean expression, and "expression1" and "expression2" are type-compatible expressions.

    First the condition is evaluated. If it is true, then the value of "expression1" is returned as the result. Otherwise the value of "expression2" is returned.

  2. A conditional expression is a ternary operation since it involves a total of 3 operands.

  3. It is the only ternary operator in C++.

  4. Example:

    int number1, number2, largerNumber;
    ....
    largerNumber = (number1 > number2 ? number1 : number2);

    This will assign the larger of the two numbers to the variable "largerNumber".

    Although the parentheses are not needed here, it is always good to include them since the conditional expression has precedence lower than most of the other operators.