问题
I'm currently trying to understand in which cases g++ warns about uninitialized variables. Consider the following piece of code:
#include <iostream>
typedef double barType;
struct foo {
barType bar;
};
int main() {
foo f;
std::cout << f.bar << std::endl;
}
If I compile it like this I get no warning:
$ g++ -O1 -Wall test.cc -o test
but if I change barType to int:
$ g++ -O1 -Wall test.cc -o test
test.cc: In function ‘int main()’:
test.cc:17: warning: ‘f.foo::bar’ is used uninitialized in this function
How can the warning depend on the type? It is uninitialized in both cases.
I'm using:
$ g++ --version
g++ (Ubuntu 4.4.1-4ubuntu9) 4.4.1
Copyright (C) 2009 Free Software Foundation, Inc.
This is free software; see the source for copying conditions. There is NO
warranty; not even for MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
Thanks,
Somebody
回答1:
It's undefined behavior, which is not required to be diagnosed, so the compiler is free to make its judgement. They could have done better.
回答2:
At a guess they might be more concerned with integral types being used uninitialized than say a float or a double since you could use integral types with pointer offsets without casting which could be very bad(tm)
回答3:
You can get this to warn if you are compiling with -O. I'm not really clear on why but if I had to guess it is for compilation speed purposes, i.e. it already need to figure this out for optimization so will only report if when you want to optimize.
There is also -Wuninitialized, which is actually not included in "all", but that that also requires -O anyway. At least if you do -Wuninitialized, the compiler will warn you that it can't warn you...
cc1plus: warning: -Wuninitialized is not supported without -O
One good takeaway from this is that -Wall is poorly named. There are other -W options not included in "all". Consult the docs for more info.
回答4:
The C++ standard doesn't mandate anything of that sort here. So compilers are free to do anything they like.
See yet another good observation here:
Fun with uninitialized variables and compiler (GCC)
来源:https://stackoverflow.com/questions/4996151/why-does-g-warning-about-uninitialized-variable-depend-on-the-type-of-the-vari