How to use the nested ternary operator in c++
We can nest ternary operators in C++. It helps in attaining the traditional else-if and the nested if functionality.
Syntax
We will show the syntax of attaining the functionality of nested if, and else-if separately below.
Nested if
condition1 ? conditon2 ? Code_Block1: Code_Block2 : Code_Block3
The syntax shows that if condition1 is true, then check condition2, else execute Code_Block3. If condition2 is true, then the Code_Block1 is executed, else Code_Block2 gets executed.
else-if
condition1 ? Code_Block1 : condition2 ? Code_Block2 : Code_Block3
The syntax shows that if condition1 is true, then Code_Block1 gets executed, else condition 2 is checked. Further, if condition2 is true, then execute Code_Block2. Otherwise, execute Code_Block3 .
Example 1: How to get nested if functionality
#include <iostream>using namespace std;int main() {int a; // Declaring variable 'a'cin>>a; // Initializing the variable 'a' using user inputstring result = a > 10 //'result' variable stores the value returned by the ternary operator? a >= 25 // Condition checked if a > 10 is true? "Greater than 25" // Executes if a >= 25 is true: "Greater than 10 but less than 25" // Executes if a >= 25 is false: "Less than or equal to 10"; // Executes if a > 10 is falsecout<<result<<endl; // Output 'result' on the screenreturn 0;}
Enter the input below
Code explanation
Line 10: We will check the first condition of the ternary operator i.e.,
a > 10.Line 11: If the condition
a > 10is true, we will check the conditiona >= 25.Line 12–13: We will return
Greater than 25ifa >= 25is true, else we will returnGreater than 10 but less than 25.Line 14: We will return
Less than or equal to 10ifa > 10is false.
Example 2: How to get else-if functionality
#include <iostream>using namespace std;int main() {int a; // Declaring variable acin>>a; // Initializing the variable with user inputstring result = a > 10 // 'result' variable stores the value// returned by the ternary operator? "Greater than 10" // Executes if a > 10 is true: a > 5 // Condition checked if a > 10 is false? "Greater than 5" // Executes if a > 5 is ture: a > 0 // Condition checked if a > 5 is false? "Greater than 0" // Executes if a > 0 is true: "Less than or equal to zero" ;// Executes if a > 0 is falsecout<<result<<endl; // Output 'result' on the screenreturn 0;}
Enter the input below
Code explanation
Line 10: We will check the first condition of the ternary operator i.e.,
a > 10.Line 12–13: We will return
Greater than 10ifa > 10is true, otherwise, we will check the conditiona > 5.Line 14–15: We will return
Greater than 5ifa > 5is true, otherwise, we will check the conditiona > 0.Line 16–17: If
a > 0is true, we will returnGreater than 0. If not, we will returnLess than or equal to zero.
Free Resources