Nesting Conditional Operations

We can nest one conditional operator inside another. That is, the conditional operator can be used as the cond or as one or both of the exprs of another conditional expression. As an example, we’ll use a pair of nested conditionals to perform a three-way test to indicate whether a grade is a high pass, an ordinary pass, or fail:

finalgrade = (grade > 90) ? "high pass"
                          : (grade < 60) ? "fail" : "pass";

The first condition checks whether the grade is above 90. If so, the expression after the ? is evaluated, which yields "high pass". If the condition fails, the : branch is executed, which is itself another conditional expression. This conditional asks whether the grade is less than 60. If so, the ? branch is evaluated and yields "fail". If not, the : branch returns "pass".

The conditional operator is right associative, meaning (as usual) that the operands group right to left. Associativity accounts for the fact that the right-hand conditional—the one that compares grade to 60—forms the : branch of the left-hand conditional expression.


Image Warning

Nested conditionals quickly become unreadable. It’s a good idea to nest no more than two or three.


..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset