c++ - 未初始化警告需要-O2

标签 c++ gcc warnings

当我编译以下 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/

相关文章:

C++。加权 std::shuffle

c# - C# 是否清理 C++ 分配的内存?

c++ - 奇怪的 GCC 编译错误(包括简单示例)

c++ - 从类模板派生的类的通用函数

c++ - 将像素缓冲区类型从 1555 转换为 5551(C++、OpenGL ES)

在 C 中使用 typeof 创建一个特定的宏

c - 编译 BASIC "libnotify"代码时出错

c - 整数指针和 'incompatible pointer type warning'

c# - MSIL 或 native 代码中的 "Unreachable code detected"

python - 如何禁用然后重新启用警告?