C++ Nested Ternary Operator

A nested ternary operator is defined as using a ternary operator inside another ternary operator. Like if-else statements, the ternary operator can also be nested inside one another.

Example of Nesting Ternary Operator in C++

In the below code, we will find the largest of three numbers using the nested ternary operator. 

C++




// C++ program to find the largest of the three number using
// ternary operator
#include <iostream>
using namespace std;
  
int main()
{
  
    // Initialize variable
    int A = 39, B = 10, C = 23;
  
    // Evaluate largest of three using ternary operator
    int maxNum
        = (A > B) ? ((A > C) ? A : C) : ((B > C) ? B : C);
  
    cout << "Largest number is " << maxNum << endl;
  
    return 0;
}


Output

Largest number is 39

As we can see it is possible to nest ternary operators in one another but the code gets complex to read and understand. So, it is generally avoided to use nested ternary operators.

Moreover, the ternary operator should only be used for short conditional code. For larger code, the other conditional statements should be preferred.



C++ Ternary or Conditional Operator

In C++, the ternary or conditional operator ( ? : ) is the shortest form of writing conditional statements. It can be used as an inline conditional statement in place of if-else to execute some conditional code.

Similar Reads

Syntax of Ternary Operator ( ? : )

The syntax of the ternary (or conditional) operator is:...

Example of Ternary Operator in C++

C++ // C++ program to illustrate the use of ternary operator #include using namespace std;    int main() {        // creating a variable     int num, test = 40;        // assigning the value of num based on the value of test     // variable     num = test < 10 ? 10 : test + 10;        printf("Num - Test = %d", num - test);        return 0; }...

C++ Nested Ternary Operator

...