当我编译以下 C++ 程序时,我需要添加 -O2
标志以获得有关未初始化变量的警告。这是为什么?
unsigned long fac(unsigned long n)
{
unsigned long product;
while (n > 1)
{
product = product * n;
n = n - 1;
}
return product;
}
➜ a g++ --version
g++ (GCC) 8.3.1 20190223 (Red Hat 8.3.1-2)
编辑:为了澄清问题,我当然启用了警告。
最佳答案
警告出现在 -O2(或任何其他优化)模式下,同时打开选项 -Wmaybe-uninitialized
。 -Wmaybe-uninitialized
选项也可以通过 -Wall
和启用的任何优化模式打开。
原因根据 GCC documentation是:
-Wmaybe-uninitialized
For an automatic (i.e. local) variable, if there exists a path from the function entry to a use of the variable that is initialized, but there exist some other paths for which the variable is not initialized, the compiler emits a warning if it cannot prove the uninitialized paths are not executed at run time. These warnings are only possible in optimizing compilation, because otherwise GCC does not keep track of the state of variables. These warnings are made optional because GCC may not be able to determine when the code is correct in spite of appearing to have an error.
然后是上述情况如何发生的示例。
关于c++ - 未初始化警告需要-O2,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56057474/