Using a Conditional Operator in an Output Expression
The conditional operator has fairly low precedence. When we embed a conditional expression in a larger expression, we usually must parenthesize the conditional subexpression. For example, we often use the conditional operator to print one or another value, depending on the result of a condition. An incompletely parenthesized conditional operator in an output expression can have surprising results:
cout << ((grade < 60) ? "fail" : "pass"); // prints pass or failcout << (grade < 60) ? "fail" : "pass"; // prints 1 or 0!cout << grade < 60 ? "fail" : "pass"; // error: compares cout to 60
The second expression uses the comparison between grade
and 60
as the operand to the <<
operator. The ...
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.