4.7. The Conditional Operator
The conditional operator (the ?: operator) lets us embed simple if-else logic inside an expression. The conditional operator has the following form:
cond ? expr1 : expr2;
where cond is an expression that is used as a condition and expr1 and expr2 are expressions of the same type (or types that can be converted to a common type). This operator executes by evaluating cond. If the condition is true, then expr1 is evaluated; otherwise, expr2 is evaluated. As one example, we can use a conditional operator to determine whether a grade is pass or fail:
string finalgrade = (grade < 60) ? "fail" : "pass";
The condition checks whether grade is less than 60. If so, the result of the expression is "fail"; otherwise the result ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access