[英]Why does this code behave differently if optimizing (-O2, -O3) is used?
I had to code some checking routines and they appear to behave differently if one uses -O0, -O1, -O2 or -O3. 我必须编写一些检查例程,如果使用-O0,-O1,-O2或-O3,它们的行为似乎不同。
Below I created a minimal example that works fine for -O0 and -O1. 下面我创建了一个适用于-O0和-O1的最小示例。 But using -O2 or -O3 the behavior changed.
但是使用-O2或-O3时行为发生了变化。 In the -O0 and -O1 case, the for-loop increments the integer and the first time it gets to the maximum, the overflow happens and the check routine triggers.
在-O0和-O1情况下,for循环递增整数,并且第一次达到最大值时,发生溢出并且检查例程触发。 In the other case the for-loop never breaks, although the integer gets negative.
在另一种情况下,for循环永远不会中断,尽管整数变为负数。
#include <iostream>
inline bool check(const int i) {
if (i < 0)
return false;
else
return true;
}
int main() {
for (int i = 0;; i += 50000000) {
std::cout << i << std::endl;
const bool succ = check(i);
if (succ == false) {
std::cout << "Overflow: " << i << std::endl;
break;
}
}
return 0;
}
Why is the compiler allowed to optimize this away? 为什么编译器允许优化它?
Trying with gcc, clang and icc, only the icc does it correct in all optimization variants the other two did not. 尝试使用gcc,clang和icc,只有icc在所有优化变体中都能正确,其他两个没有。
Signed integer overflow gives undefined behavior . 有符号整数溢出会产生未定义的行为 。 Thus, the compiler has free reign to implement this case as they like.
因此,编译器可以自由地执行这种情况,因为他们喜欢。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.