Open In App

C++ Ternary or Conditional Operator

Last Updated : 31 Jul, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

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.

Syntax of Ternary Operator ( ? : )

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

expression ? statement_1 : statement_2;

As the name suggests, the ternary operator works on three operands where

  • expression: Condition to be evaluated.
  • statement_1: Statement that will be executed if the expression evaluates to true.
  • statement_2: Code to be executed if the expression evaluates to false.

// image

The above statement of the ternary operator is equivalent to the if-else statement given below:

if ( condition ) {
statement1;
}
else {
statement2;
}

Example of Ternary Operator in C++

C++




// C++ program to illustrate the use of ternary operator
#include <iostream>
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;
}


Output

Num - Test = 10

In the above code, we have used the ternary operator to assign the value of the variable num depending upon the value of another variable named test.

Note: The ternary operator have third most lowest precedence, so we need to use the expressions such that we can avoid errors due to improper operator precedence management.

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.



Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads