c - C99 标准是否允许编译器转换代码,以便在满足某些推导条件后不再评估相同的表达式?

标签 c optimization c99 compiler-optimization

我不太明白 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 */

请注意,found0 开头,可以保持不变或变为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 和循环控制表达式第一次迭代之后的不需要计算表达式的一部分,标准是怎么说的哪个控件进入if

很明显,如果在这段代码之后的某处使用了 found,编译器必须发出遍历数组并有条件地计算 found = 1 表达式的代码。

实现是否需要为数组中找到的每个零评估一次 found = 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 的“纯”函数;也就是说,它们没有副作用,它们的结果完全取决于参数。假设编译器也认为 otherPureFunction 是一个极其昂贵的操作。编译器可以选择像您编写的那样实现代码:

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

也就是说,确定在某些情况下不需要计算 otherPureFunction(),因为一旦已知左操作数为零,乘法的结果就已知了。不需要的副作用将被忽略,因为没有副作用。

关于c - C99 标准是否允许编译器转换代码,以便在满足某些推导条件后不再评估相同的表达式?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23518461/

相关文章:

c++ - 在 c/c++ 中通过函数在内存中的地址调用函数

从程序集调用 printf - 不工作

c - 用户未与 Richtextbox 交互

c# - 有哪些方法可以动态获取 DateTime.Now.AddDays(0..7) 的列表?

c++ - 定义静态全局数组以避免在函数中定义它

C90 编译器提示没有原型(prototype)函数警告

mysql - 海量记录更新——性能优化

c - c99 中结构体数组的数组

c99 - 错误 : unknown type name ‘pid_t’

c - header 中的 EXPORT_SYMBOL 导致 "exported twice"错误