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