net*_*ent 3 c++ compiler-optimization internal-compiler-error
以以下最小示例为例:
#include <stdio.h>
bool test(){
for (int i = 0; i < 1024; i++)
{
printf("i=%d\n", i);
}
}
int main(){
test();
return 0;
}
Run Code Online (Sandbox Code Playgroud)
test函数中的 return 语句丢失的地方。如果我像这样运行示例:
g++ main.cpp -o main && ./main
Run Code Online (Sandbox Code Playgroud)
然后循环在 1024 次迭代后中止。但是,如果我在打开优化的情况下运行示例:
g++ -O3 main.cpp -o main && ./main
Run Code Online (Sandbox Code Playgroud)
然后这是优化的,我得到一个无限循环。
此行为在g++version10.3.1和clang++version之间保持一致10.0.1。如果我添加 return 语句或将函数的返回类型更改为void.
我很好奇:这会被认为是编译器错误吗?或者这是可以接受的,因为缺少 return 语句是未定义的行为,因此我们失去了对这个函数中发生的事情的所有保证?
您的函数被声明为bool test(),但您的定义从不返回任何内容。这意味着你已经违反了与语言的约定,并在未定义的行为领域被暂停了。在那里,所有结果都是“正确的”。