#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;
}
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?
It is worth noting that Clang catches it:
main.cpp:13:12: warning: variable 't' is uninitialized when used here [-Wuninitialized]
v[i] = t++;
^
Used g++ (GCC) 7.2.1 20170915 (Red Hat 7.2.1-2).
Used clang version 4.0.1 (tags/RELEASE_401/final).
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.
g++'s warning flag is not called -Wuninitialized
: it is called -Wmaybe-uninitialized
.
Also, as Jonathan Wakely noted in his answer, g++ is able to detect usage of uninitialized variables only when optimizations are enabled.
Enabling both -Wmaybe-initalized
and optimizations produces the expected warning: https://godbolt.org/g/3CZ6kT
Note that -Wmaybe-initalized
is enabled by default with both -Wall
and -Wextra
.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With