Ternary Operator in C++

In this tutorial, we are going to learn about the ternary operator in C++. It uses three operands for its operation. It is also known as the conditional operator.

Ternary Operator in C++

The ternary operator is used in C++ to implement an if-else statement in a single line of code. The syntax for it will be as follows.

Syntax:

operand-1 ? operand-2 : operand-3

In the above expression if operand-1 returns true, then operand-2 is evaluated and if operand-1 returns false, then operand-3 is evaluated. See an example here.

(5>3) ? cout << “5 is greater than 3.\n” : cout<<“False statement\n”

 

Since 5 is greater than 3 and (5>3) returns true, the program must print “5 is greater than 3”.

See the implementation here.

#include <iostream>
using namespace std;

int main()
{
  (5>3) ? cout << "5 is greater than 3.\n" : cout << "False statement\n";
  return 0;
}

Output:

 5 is greater than 3.

Nested ternary operators in C++

We can also use ternary operators to implement nested if-else statements. Let’s understand this with an example.

Suppose we are taking three integer inputs from the user and we have to find the greatest of these three. Now an if-else implementation of the above example would be like this.

#include <iostream>
using namespace std;

int main()
{
  int a,b,c,max;
  cout<<"Enter three integers.\n";
  cin>> a>> b>>c;
  if(a>b)
  {
    	if(a>c)
    	max=a;
    	else
    	max=c;
  }
  else
  {
    if(b>c)
    max=b;
    else
    max=c;
  }
  cout<< "Maximum of the given three integers is "<<max<<endl;
  return 0;
}

Output:

Enter three integers.
34 67 3
Maximum of the given three integers is 67

Now, let’s do it using the ternary operator. The implementation would be like this.

#include <iostream>
using namespace std;

int main()
{
  int a,b,c,max;
  cout<<"Enter three integers.\n";
  cin>> a>> b>>c;
  max= (a>b) ? (a>c?a:c) : (b>c?b:c);
  cout<< "Maximum of the given three integers is "<<max<<endl;
  return 0;
}

In the above example, we have used nested conditional operators to find the largest element of the given inputs. The program will print the maximum of the given integers. See the output.

Enter three integers.
34 67 3
Maximum of the given three integers is 67

Thank you.

You may also read:

Leave a Reply