为什么 GCC 不报告未初始化的变量

Why GCC does not report uninitialized variable?

本文关键字:初始化 变量 报告 GCC 为什么      更新时间:2023-10-16
#include <ios>
#include <iostream>
#include <map>
using namespace std;
int main() {
  ios_base::sync_with_stdio(false);
  map<int, int> v;
  int i;
  int t;
  while (cin >> i) {
    v[i] = t++;
  }
  auto mi = i;
  auto mt = t;
  for (const auto p : v) {
    if (p.second < mt) {
      mi = p.first;
      mt = p.second;
    }
  }
  cout << mi << 'n';
  return 0;
}

上述程序大量使用未初始化的变量t,但GCC没有用-Wall或-Wuninitialized报告它。为什么会这样?

值得注意的是,叮当抓住了它:

main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
    v[i] = t++;
           ^

使用 g++ (GCC( 7.2.1 20170915(Red Hat 7.2.1-2(。

使用的 clang 版本 4.0.1(标签/RELEASE_401/最终(。


正如您在 https://godbolt.org/g/kmYMC1 中看到的,GCC 7.2 即使在应该报告时也不会报告它。我将在 GCC 的问题跟踪器中创建一张票证。

g

++的警告标志不叫-Wuninitialized:它叫-Wmaybe-uninitialized

此外,正如Jonathan Wakely在他的回答中指出的那样,g++只有在启用优化时才能检测未初始化变量的使用情况。

同时启用-Wmaybe-initalized和优化会产生预期的警告:https://godbolt.org/g/3CZ6kT

请注意,默认情况下,-Wmaybe-initalized 同时启用 -Wall-Wextra

GCC 只能在启用优化时检测未初始化的变量,因为跟踪变量值的逻辑是优化机制的一部分。

如果使用-O -Wall进行编译,则会收到警告:

<source>: In function 'int main()':
12 : <source>:12:13: warning: 't' may be used uninitialized in this function [-Wmaybe-uninitialized]
     v[i] = t++;
            ~^~
Compiler exited with result code 0

https://godbolt.org/g/327bsi