Skip to main content
Engineering LibreTexts

6.6: Ternary operator

  • Page ID
    29062
  • Conditional or Ternary Operator (?:) in C/C++

    The conditional operator is kind of similar to the if-else statement as it does follow the same algorithm as of if-else statement but the conditional operator takes less space and helps to write the if-else statements in the shortest way possible.

    The conditional operator is of the form

    variable = Expression1 ? Expression2 : Expression3

    In this statement Expression1 is the condition. If the condition is true, then variable is assigned the value from Expression2, else variable is assigned the value of Expression2. It would be the same as:

    if(Expression1)
    {
        variable = Expression2;
    }
    else
    {
        variable = Expression3;
    }
    

    Since the Conditional Operator ‘?:’ takes three operands to work, it is also called ternary operators.

    #include <iostream>
    using namespace std;
    
    int main()
    {
        // variable declaration
        int num1 = 5, num2 = 10, maxNum;
    
        // If num1 > num2 
        //    maxNum = num1
        // else 
        //    maxNum = num2
        maxNum = (num1 > num2) ? num1 : num2;
    
        // Print the largest number
        cout << "Largest number between "
            << num1 << " and "
            << num2 << " is "
            << maxNum << endl;
        return 0;
    } 

    In this case the output would be:

    Largest number between 5 and 10 is 10

    Adapted from: 
    "Conditional or Ternary Operator (?:) in C/C++" by khalidbitdGeeks for Geeks is licensed under CC BY-SA 4.0 

    • Was this article helpful?