开发者

Why does g++ warning about uninitialized variable depend on the type of the variable? (it warns for an int but not for a double)

I'm currently trying to understand in which cases g++ warns about uninitialized variab开发者_如何学编程les. 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


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.


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)


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.


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)

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜