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, ...

Get C++ Primer, Fifth Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.