The conditional operator is the only ternary operator in C++(www.cppentry.com). It allows us to embed simple if-else tests inside an expression. The conditional operator has the following syntactic form
- cond expr1 : expr2;
where cond is an expression that is used as a condition (Section 1.4.1, p. 12). The operator executes by eva luating cond. If cond eva luates to 0, then the condition is false; any other value is true. cond is always eva luated. If it is true, then expr1 is eva luated; otherwise, expr2 is eva luated. Like the logical AND and OR (&& and ||) operators, the conditional operator guarantees this order of eva luation for its operands. Only one of expr1 or expr2 is eva luated. The following program
illustrates use of the conditional operator:
- int i = 10, j = 20, k = 30;
-
int maxVal = i > j i : j;
注意:不要写出 (a > b) true : false 这种多余的条件操作符,直接写 (a > b) 即可。
Avoid Deep Nesting of the Conditional Operator
We could use a set of nested conditional expressions to set max to the largest of three variables:
- int max = i > j
- i > k i : k
- : j > k j : k;
We could do the equivalent comparison in the following longer but simpler way:
- int max = i;
- if (j > max)
- max = j;
- if (k > max)
- max = k;
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, the conditional operator is often used to print one or another value, depending on the result of a condition. Incompletely parenthesized uses of the conditional operator in an output expression can have surprising results:
- cout << (i < j i : j);
- cout << (i < j) i : j;
- cout << i < j i : j;
The second expression is the most interesting: It treats the comparison between i and j as the operand to the << operator. The value 1 or 0 is printed, depending on whetheri < jis true or false. The << operator returns cout, which is tested as the condition for the conditional operator. That is, the second expression is equivalent to
- cout << (i < j);
- cout i : j;
-
EXERCISES SECTION 5.7
Exercise 5.20: Write a program to prompt the user for a pair of numbers and report which is smaller.
Exercise 5.21: Write a program to process the elements of a vector<int>. Replace each element with an odd value by twice that value.