I noticed this interesting behaviour of the g++ compiler, if I add a -O3 flag to the compiler, I get
otsu.cpp:220: warning: ‘x’ may be used uninitialized in this function
However, when I do not use optimization and instead use a debug flag -g I got no warnings at all. Now, I trust the compiler more when the -g flag is on; however, I'm wondering if this is well defined behaviour that should be expected?
For clarity, the code that causes this is something along these lines:
int x; //uninitialized
getAValueForX( &x ); // function makes use of x,
// but x is unitialized
where
void getAValueForX( int *x )
{
*x = 4;
}
or something along those lines, obviously more complex.
If the value of y is always 1, 2 or 3, then x is always initialized, but GCC doesn't know this. To suppress the warning, you need to provide a default case with assert(0) or similar code. This option also warns when a non-volatile automatic variable might be changed by a call to longjmp.
You can request many specific warnings with options beginning with ' -W ', for example -Wimplicit to request warnings on implicit declarations. Each of these specific warning options also has a negative form beginning ' -Wno- ' to turn off warnings; for example, -Wno-implicit .
gcc -Wall enables all compiler's warning messages. This option should always be used, in order to generate better code.
By default, Fuchsia C/C++ code compiles with the flag -Wconversion , which prohibits implicit type conversions that may alter a value.
That's expected. The optimizations cause a specific code analysis to run and that's how gcc finds the un-initialized variables. It's in the manual page:
. . . these warnings depend on optimization
http://gcc.gnu.org/onlinedocs/gcc/Warning-Options.html
This is actually very common with gcc. And yes, this is to be expected.
As far as I understood, in order to optimize, the compiler generates a lot of metrics and transform the code (or, more precisely, the representation it has of the code) in a way that allows the detection of uninitialized or unused variables for examples (there are a few other warnings like that, I don't remember the list).
Doing the same thing without optimization would require doing, and then scrapping away all this analysis. This would slow down compilation significantly for no good purpose (especially as, in debug, the compiler is not suppose to rearrange the code).
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