Team LiB
Previous Section Next Section

5.7. The Conditional Operator

5.7. 条件操作符

The conditional operator is the only ternary operator in C++. It allows us to embed simple if-else tests inside an expression. The conditional operator has the following syntactic form

条件操作符是 C++ 中唯一的三元操作符,它允许将简单的 if-else 判断语句嵌入表达式中。条件操作符的语法格式为:

     cond ? expr1 : expr2;

where cond is an expression that is used as a condition (Section 1.4.1, p. 12). The operator executes by evaluating cond. If cond evaluates to 0, then the condition is false; any other value is true. cond is always evaluated. If it is true, then expr1 is evaluated; otherwise, expr2 is evaluated. Like the logical AND and OR (&& and ||) operators, the conditional operator guarantees this order of evaluation for its operands. Only one of expr1 or expr2 is evaluated. The following program illustrates use of the conditional operator:

其中,cond 是一个条件判断表达式(第 1.4.1 节)。条件操作符首先计算 cond 的值,如果 cond 的值为 0,则条件为 false;如果 cond 非 0,则条件为 true。无论如何,cond 总是要被计算的。然后,条件为 true 时计算 expr1 ,否则计算 expr2 。和逻辑与、逻辑或(&&||)操作符一样,条件操作符保证了上述操作数的求解次序。expr1expr2 中只有一个表达式被计算。下面的程序说明了条件操作符的用法:

     int i = 10, j = 20, k = 30;
     // if i > j then maxVal = i else maxVal = j
     int maxVal = i > j ? i : j;

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:

可以使用一组嵌套的条件操作符求出三个变量的最大值,并将最大值赋给 max

     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);  // ok: prints larger of i and j
     cout << (i < j) ? i : j;  // prints 1 or 0!
     cout << i < j ? i : j;    // error: compares cout to int

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 whether i < j is 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

第二个表达式比较有趣:它将i和j的比较结果视为 << 操作符的操作数,输出 1 或 0。 << 操作符返回 cout 值,然后将返回结果作为条件操作符的判断条件。也就是,第二个表达式等效于:

     cout << (i < j); // prints 1 or 0
     cout ? i : j;    // test cout and then evaluate i or j
                      // depending on whether cout evaluates to true or false

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.

编写程序处理 vector<int> 对象的元素:将每个奇数值元素用该值的两倍替换。


Team LiB
Previous Section Next Section