设为首页 加入收藏

TOP

5.10.3 Order of eva luation (1)
2013-10-07 15:24:48 来源: 作者: 【 】 浏览:72
Tags:5.10.3 Order eva luation

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

  1. // iter only dereferenced if it isn’t at end  
  2. 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

  1. 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:

  1. // oops! language does not define order of eva luation  
  2. 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:

  1. if (ia[0] < ia[0]) // execution if rhs is eva luated first  
  2. if (ia[0] < ia[1]) // execution if lhs is eva luated first 

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.

】【打印繁体】【投稿】【收藏】 【推荐】【举报】【评论】 【关闭】 【返回顶部
分享到: 
上一篇5.10.3 Order of eva luation (2) 下一篇2.3.4 Variable Initialization R..

评论

帐  号: 密码: (新用户注册)
验 证 码:
表  情:
内  容:

·Sphinx : 高性能SQL (2025-12-24 10:18:11)
·Pandas 性能优化 - (2025-12-24 10:18:08)
·MySQL 索引 - 菜鸟教 (2025-12-24 10:18:06)
·Shell 基本运算符 - (2025-12-24 09:52:56)
·Shell 函数 | 菜鸟教 (2025-12-24 09:52:54)