简体   繁体   English

如果使用优化(-O2,-O3),为什么此代码的行为会有所不同?

[英]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循环永远不会中断,尽管整数变为负数。

Code

#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.

相关问题 为什么 GCC 删除了我在 O3 上的代码,而不是在 O0 上? - Why does GCC delete my code on O3 but not on O0? 为什么clang中的-O2或更高优化会破坏这段代码? - Why does -O2 or greater optimization in clang break this code? g++ 优化:O2 标志修复了 O3 再次破坏的损坏代码 - g++ Optimization : O2 flag fixes a broken code where O3 breaks it again 具有不匹配的优化级别(-O3、-O2、-O1、-O0)的二进制文件是否会导致稳定性问题? - Does having binaries with mismatched optimization levels (-O3, -O2, -O1, -O0) cause stability issues? 在比较Java与C ++的速度时,应该使用-O3或-O2编译C ++代码吗? - When comparing Java with C++ for speed should I compile the C++ code with -O3 or -O2? gcc优化标志-O3使代码比-O2慢 - gcc optimization flag -O3 makes code slower than -O2 优化代码时编译器在汇编中做了什么?即-O2标志 - What does the compiler do in assembly when optimizing code? ie -O2 flag 为什么gcc链接程序对.a文件和.o文件的行为有所不同? - Why does the gcc linker behave differently with .a files and .o files? 使用-O2或-O3标志编译时未捕获到异常 - Exception not caught when compiled with -O2 or -O3 flag 为什么gcc -O1的行为与gcc -O0 +选项不同 - Why does gcc -O1 behave differently than gcc -O0 + options
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM