C++ - Nested Ternary Operator
C++ - Nested Ternary Operator
Ternary operator also known as conditional operator uses three operands to perform operation.
Syntax :
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
1. 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
if ( a )
then b execute
else
c execute
Example:
Output:
2. 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
: i
▲
Output:
3. 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
: e
if ( a )
if ( b )
c execute
else
d execute
else
e execute
Output: