Team LiB
Previous Section Next Section

5.9. Comma Operator

5.9. 逗号操作符

A comma expression is a series of expressions separated by commas. The expressions are evaluated from left to right. The result of a comma expression is the value of the rightmost expression. The result is an lvalue if the rightmost operand is an lvalue. One common use for the comma operator is in a for loop.

逗号表达式是一组由逗号分隔的表达式,这些表达式从左向右计算。逗号表达式的结果是其最右边表达式的值。如果最右边的操作数是左值,则逗号表达式的值也是左值。此类表达式通常用于for循环:

     int cnt = ivec.size();
     // add elements from size... 1 to ivec
     for(vector<int>::size_type ix = 0;
                     ix != ivec.size(); ++ix, --cnt)
         ivec[ix] = cnt;

This loop increments ix and decrements cnt in the expression in the for header. Both ix and cnt are changed on each trip through the loop. As long as the test of ix succeeds, we reset the next element to the current value of cnt.

上述的 for 语句在循环表达式中使 ix 自增 1 而 cnt 自减 1。每次循环均要修改 ixcnt 的值。当检验 ix 的条件判断成立时,程序将下一个元素重新设置为 cnt 的当前值。

Exercises Section 5.9

Exercise 5.24:

The program in this section is similar to the program on page 163 that added elements to a vector. Both programs decremented a counter to generate the element values. In this program we used the prefix decrement and the earlier one used postfix. Explain why we used prefix in one and postfix in the other.

本节的程序与第 5.5 节vector 对象中添加元素的程序类似。两段程序都使用递减的计数器生成元素的值。本程序中,我们使用了前自减操作,而第 5.5 节的程序则使用了后自减操作。解释为什么一段程序中使用前自减操作而在另一段程序中使用后自减操作。

Team LiB
Previous Section Next Section