C++ | Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation.
Syntax :
op1 ? op2 : op3;
Nested Ternary operator: Ternary operator can be nested. A nested ternary operator can have many forms like :
- a ? b : c
- a ? b: c ? d : e ? f : g ? h : i
- a ? b ? c : d : e
Let us understand the syntaxes one by one :
- a ? b : c => This ternary operator is similar to if-else statement. So it can be expressed in form of if-else statement.
Expression using Ternary operator:a ? b : c
Expression using if else statement:
if ( a ) then b execute else c executeExample:
// C++ program to illustrate// nested ternary operators#include <bits/stdc++.h>usingnamespacestd;intmain(){cout <<"Execute expression using"<<" ternary operator: ";// Execute expression using// ternary operatorinta = 2 > 5 ? 2 : 5;cout << a << endl;cout <<"Execute expression using "<<"if else statement: ";// Execute expression using if elseif( 2 > 5)cout <<"2";elsecout <<"5";return0;}Output:Execute expression using ternary operator: 5 Execute expression using if else statement: 5
- a ? b: c ? d : e ? f : g ? h : i =>This Nested ternary operator can be broken into if, else and else-if statement. The expression can break into smaller piece in ternary operator and if else statement which are given below:
Expression using ternary operator:a ? b : c ? d : e ? f : g ? h : iExpression using if else statement:
if a then b else if c then d else if e then f else if g then h else i// C++ program to illustrate// nested ternary operators#include <bits/stdc++.h>usingnamespacestd;intmain(){cout <<"Execute expression using "<<"ternary operator: ";inta = 2 > 3 ? 2 : 3 > 4 ? 3 : 4;cout << a << endl;cout <<"Execute expression using "<<"if else statement: ";if( 2 > 3 )cout <<"2";elseif( 3 > 4 )cout <<"3";elsecout <<"4";return0;}Output:Execute expression using ternary operator: 4 Execute expression using if else statement: 4
- a ? b ? c : d : e => Below is the expansion of expression using ternary operator and if else statement.
Expression using ternary operator:a ? b ? c : d : eExpression using if else statement:
if ( a ) if ( b ) c execute else d execute else e execute// C++ program to illustrate// nested ternary operators#include <bits/stdc++.h>usingnamespacestd;intmain(){cout <<"Execute expression using "<<"ternary operator: ";inta = 4 > 3 ? 2 > 4 ? 2 : 4 : 3;cout << a << endl;cout <<"Execute expression using "<<"if else statement: ";if( 4 > 3 )if( 2 > 4 )cout <<"2";elsecout <<"4";elsecout <<"3";return0;}Output:Execute expression using ternary operator: 4 Execute expression using if else statement: 4
Take a step-up from those “Hello World” programs. Learn to implement data structures like Heap, Stacks, Linked List and many more! Check out our Data Structures in C course to start learning today.


