Conditional Operator (?:)

C++ provides the conditional operator (?:), which is closely related to the if...else statement. The conditional operator is C++’s only ternary operator—it takes three operands. The operands, together with the conditional operator, form a conditional expression. The first operand is a condition, the second operand is the value for the entire conditional expression if the condition is true and the third operand is the value for the entire conditional expression if the condition is false. For example, the output statement

cout << ( grade >= 60 ? "Passed" : "Failed" );

contains a conditional expression, grade >= 60 ? "Passed" : "Failed", that evaluates to the string "Passed" if the condition grade >= 60 is true, but evaluates to "Failed" if the condition is false. Thus, the statement with the conditional operator performs essentially the same as the preceding if...else statement. As we’ll see, the precedence of the conditional operator is low, so the parentheses in the preceding expression are required.


Image Error-Prevention Tip 4.2

To avoid precedence problems (and for clarity), place conditional expressions (that appear in larger expressions) in parentheses.


The values in a conditional expression also can be actions to execute. For example, the following conditional expression also prints "Passed" or "Failed":

grade >= 60 ? cout << "Passed" : cout << "Failed";

The preceding conditional expression is read, “If grade is greater than or equal to 60, then cout << "Passed"; otherwise, cout << "Failed".” This, too, is comparable to the preceding if...else statement. Conditional expressions can appear in some program contexts where if...else statements cannot.

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

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