We can nest ternary operators in C++. It helps in attaining the traditional else-if
and the nested if
functionality.
We will show the syntax of attaining the functionality of nested if
, and else-if
separately below.
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
.
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
Line 10: We will check the first condition of the ternary operator i.e., a > 10
.
Line 11: If the condition a > 10
is true, we will check the condition a >= 25
.
Line 12–13: We will return Greater than 25
if a >= 25
is true, else we will return Greater than 10 but less than 25
.
Line 14: We will return Less than or equal to 10
if a > 10
is false.
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
Line 10: We will check the first condition of the ternary operator i.e., a > 10
.
Line 12–13: We will return Greater than 10
if a > 10
is true, otherwise, we will check the condition a > 5
.
Line 14–15: We will return Greater than 5
if a > 5
is true, otherwise, we will check the condition a > 0
.
Line 16–17: If a > 0
is true, we will return Greater than 0
. If not, we will return Less than or equal to zero
.
Free Resources