为什么GCC不报告未初始化的变量? [英] Why GCC does not report uninitialized variable?

查看:238
本文介绍了为什么GCC不报告未初始化的变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

#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报告它。

The abovementioned program makes heavy use of an uninitialized variable t, but GCC does not report it with -Wall or -Wuninitialized. Why is it so?

值得注意的是Clang抓住了它:

It is worth noting that Clang catches it:

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)。

Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).

使用的clang版本4.0.1(标签/ RELEASE_401 / final)。

Used clang version 4.0.1 (tags/RELEASE_401/final).

您可以在 https://godbolt.org/g/kmYMC1即使应有,GCC 7.2也不会报告。我将在GCC的问题跟踪器中创建票证。

As you can see in https://godbolt.org/g/kmYMC1 GCC 7.2 does not report it even when it should. I will create a ticket in GCC's issue tracker.

推荐答案

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

GCC can only detect uninitialized variables when optimization is enabled, because the logic for tracking the values of variables is part of the optimization machinery.

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

If you compile with -O -Wall you get a warning:

<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

这篇关于为什么GCC不报告未初始化的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆