加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

C99 Standard是否允许编译器转换代码,以便在满足某些推断条件后

发布时间:2020-12-16 10:09:36 所属栏目:百科 来源:网络整理
导读:我不太了解5.1.2.3/3的以下部分: An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or access
我不太了解5.1.2.3/3的以下部分:

An actual implementation need not evaluate part of an expression if it can deduce that its
value is not used and that no needed side effects are produced (including any caused by
calling a function or accessing a volatile object).

假设我有以下代码:

char data[size];
int i;
int found;
/* initialize data to some values in here */
found = 0;
for( i = 0; i < size; i++ ) {
   if( data[i] == 0 ) {
      found = 1;
      /* no break in here */
   }
}
/* i no longer used,do something with "found" here */

请注意,found从0开始,可以保持不变或变为1.它不能变成1然后变成其他东西.所以下面的代码会产生相同的结果(除了i值之外,无论如何都不会在循环之后使用):

char data[size];
int i;
int found;
/* initialize data to some values in here */
found = 0;
for( i = 0; i < size; i++ ) {
   if( data[i] == 0 ) {
      found = 1;
      break;
   }
}
/* i no longer used,do something with "found" here */

现在标准所说的不需要评估关于found = 1的表达式的一部分以及第一次迭代之后的循环控制表达式,其中控制进入内部,如果?

显然,如果在此代码之后的某处使用found,则编译器必须发出遍历数组的代码并有条件地计算found = 1表达式.

对于在数组中找到的每个零,是否需要对find = 1进行一次评估,或者它是否可以将其评估为一次,因此在编译第一个片段时有效地为第二个片段发出代码?

解决方法

can it instead evaluate it no more that once and so effectively emit the code for the second snippet when compiling the first snippet?

是的,编译器有权执行该优化.这似乎是一个非常积极的优化,但它是合法的.

看一个更符合文本精神的例子可能会很有趣:

An actual implementation need not evaluate part of an expression if it can deduce that its value is not used and that no needed side effects are produced (including any caused by calling a function or accessing a volatile object).

假设我们有:

int x = pureFunction(y) * otherPureFunction(z);

假设编译器知道两个函数都是int返回“纯”函数;也就是说,它们没有副作用,它们的结果完全取决于论点.假设编译器还认为其他PureFunction是一个非常昂贵的操作.编译器可以选择像您编写的那样实现代码:

int temp = pureFunction(y);
int x = temp == 0 ? 0 : temp * otherPureFunction(z);

也就是说,确定在某些条件下没有必要计算otherPureFunction(),因为一旦知道左操作数为零,乘法的结果就已经知道了.没有必要的副作用将被省略,因为没有副作用.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读