|
In Section 5.2 (p. 152) we saw that the && and || operators specify the order in which their operands are eva luated: In both cases the right-hand operand is eva luated if and only if doing so might affect the truth value of the overall expression.
Because we can rely on this property, we can write code such as -
- while (iter != vec.end() && *iter != some_val)
The only other operators that guarantee the order in which operands are eva luated are the conditional ( :) and comma operators. In all other cases, the order is unspecified.
For example, in the expression - f1() * f2();
we know that both f1 and f2 must be called before the multiplication can be done. After all, their results are what is multiplied. However, we have no way to know whether f1 will be called before f2 or vice versa.
注意:括号只能改变运算的优先级(参见英文原版书第169 页), 不能改变求值的顺序。例如,f()+g()-h() 和f()+(g()-h()) 两种写法的运算优先级不同,但求值顺序(即先调用哪个函数)有可能相同。
The order of operand eva luation matters if one subexpression changes the value of an operand used in another subexpression: -
- if (ia[index++] < ia[index])
The behavior of this expression is undefined. The problem is that the left- and right-hand operands to the < both use the variable index. However, the left-hand operand involves changing the value of that variable. Assuming index is zero, the compiler might eva luate this expression in one of the following two ways: - if (ia[0] < ia[0])
- if (ia[0] < ia[1])
We can guess that the programmer intended that the left operand be eva luated, thereby incrementing index. If so, the comparison would be between ia[0] and ia[1]. The language, however, does not guarantee a left-to-right eva luation order. In fact, an expression like this is undefined. An implementation might eva luate the right-hand operand first, in which case ia[0] is compared to itself. Or the implementation might do something else entirely.
|