|
A comma expression is a series of expressions separated by commas. The expressions are eva luated fromleft 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. - int cnt = ivec.size();
-
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.
注意:用逗号表达式来缩短代码行数通常是个坏主意。
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 programwe used the prefix decrement and the earlier one used postfix. Explain why we used prefix in one and postfix in the other.
|