Information Technology Reference
In-Depth Information
The Conditional Operator
The conditional operator is a powerful and succinct way of returning one of two values, based
on the result of a condition. The operator is shown is Table 8-15.
The conditional operator is ternary.
Table 8-15. The Conditional Operator
Operator
Name
Description
? :
Conditional operator
Evaluates an expression and returns one of two values,
depending on whether the expression returns true or false .
The syntax for the conditional operator is shown following. It has a test expression and two
result expressions.
￿ f Condition evaluates to true , then Expression1 is evaluated and returned. Otherwise,
Expression2 is evaluated and returned.
Expression Condition must return a value of type bool .
￿
Condition ? Expression1 : Expression2
The conditional operator can be compared with the if...else construct. For example, the
following if...else construct checks a condition, and if the condition is true, it assigns 5 to
variable IntVar . Otherwise it assigns it the value 10 .
if( x < y ) // if...else
IntVar = 5;
else
IntVar = 10;
The conditional operator can perform the same operation in a less verbose form, as shown
in the following statement:
IntVar = x < y ? 5 : 10; // Conditional operator
Search WWH ::




Custom Search