# Conditional or Ternary Operator (?:) in C++

August 18, 2022, Learn eTutorial
1398

In C++, the conditional operator returns one value if the condition is true and another value if the condition is false. This operator is also referred to as a Ternary Operator.

## The syntax for conditional operators

``````
(condition)  ?  true_value  :  false_value;
```
```

The condition will be written in place of the condition in the above syntax; if the condition is true, the true value will be executed; if the condition is false, the false value will be executed.

## Example for Ternary Operators

Now consider an example to gain a better understanding.

A conditional operator is used in a C++ program to find the largest number between the values of two integer variables.

``````
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
int a=20,b=7,c;

c=(a>b) ? a : b;
cout<<"Greatest number is "<<c;
return 0;
}```
```

Output:

```Greatest number is 20
```

Because the condition `(a>b) `is true, the statement was written just after the `?` marks will execute and the value of a will be stored in c.

## Nested conditional operator

By adding a conditional expression as a second (after?) or third part (after:) of the ternary operator, it is possible to create nested conditional operators.

### The syntax for nested conditional operators in C++

``````
1.(condition)  ?  ((condition)  ? true_value :  false_value) : false_value;

2.(condition)  ?  true_value : ((condition)  ? true_value :  false_value);
```
```

On line 1 of the above two syntaxes, you can see that if the first condition is true, we are checking another condition just after the? mark of the first condition. Similarly, on line 2, if the first condition is true, the true value is executed; if it is false, we check another condition just after the: mark of the first condition.

Using the nested conditional operator, a C++ program is written to find the greatest number among the values of three integer variables.

``````
#include <iostream>
#include <conio.h>

using namespace std;

int main()
{
int a=20,b=50,c=26,g;

c=(a>b && a>c) ? a : ((b>a && b>c) ? b : c);
cout<<"So the greatest number is "<<c;
return 0;
}```
```

Output:

```So the greatest number is 50
```

The condition (a>b && a>c) is false here, so we check another condition (b>a && b>c) that is written immediately after the: marks of the first condition, and the condition is true this time, so the value of b is stored in c.

VIEW ALL
VIEW ALL
VIEW ALL