为什么 GCC 不报告未初始化的变量
Why GCC does not report uninitialized variable?
#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
相关文章:
- 初始值设定项列表是否只接受使用相同类型的值初始化变量?
- 在 C++ 中访问 lambda 捕获初始化变量
- 为什么C++不支持对未初始化变量进行智能分析?
- 使用 clang++ 和 g++ 在C++中初始化变量
- C++使用 lambda 初始化变量
- 如何在初始化列表中的构造函数之后初始化变量/对象?
- C++ - 输出与初始化变量不同?
- C++/Win32 构造函数不使用从对话框获取的字符串初始化变量
- 在C++中,为什么int可以使用new运算符初始化变量,而double不能
- 具有静态存储持续时间的常量初始化变量的初始化顺序
- C++ 中的初始化变量
- C++中未初始化变量的值
- 如何在需要提及需要循环声明的其他类的类中初始化变量?
- 我想知道在构造函数中初始化变量时的生命周期
- 读取恰好具有良好值的未初始化变量
- 如何在 getter 的父类中初始化变量的情况下访问子类中的变量
- 为什么在 c++ 中有多种初始化变量的方法
- 没有参数的默认构造函数是否总是初始化变量?
- 是否可以使用 lambda 初始化变量(删除复制 ctor 时)
- 使用构造函数跳闸UB的新放置后使用初始化变量