ilteris kaplan blog

Archive of blog posts since 2005

April 5, 2008

Wiki

Conditional Operator

#wiki

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 the string “Failed” if the condition is false. Thus, the statement with the conditional operator performs essentially the same as the preceding if…else statement.

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 locations where if…else statements cannot.

Continue Reading

Back to Archive