So let's say I'm careless and make a stupid typo.. this file:
test.c
#include <stdio.h>
int main()
{
int x = x;
printf("%d\n",x);
}
compiles fine:
mymachine:~ oll$ gcc test.c
mymachine:~ oll$ ./a.out
1782198366
Obviously int x = x
is a mistake but the compiler accepts this without warning. I've wasted quite a few hours trying to this error.
Is there a compiler flag that and can use for gcc / g++ to make the compiler give me a warning when I use an uninitialised stack variable? This could potentially save me a lot of time in the future.
I have tried gcc -O -Wuninitialized test.c
- didn't work.
Thanks in advance
Edit: I have tried -Wall
, no mention of x
mymachine:~ oll$ gcc -Wall test.c
test.c: In function ‘main’:
test.c:7: warning: control reaches end of non-void function
Edit: Solution found
It seems that using the command line tools gcc
and g++
in OS X 10.8 doesn't give this warning, using clang
works:
mymachine:~ oll$ clang -Wall test.c
test.c:5:10: warning: variable 'x' is uninitialized when used within its own initialization [-Wuninitialized]
int x = x;
~ ^
1 warning generated.
It looks like the warning flags you want are -Wuninitialized -Winit-self
(see it live):
Warn about uninitialized variables that are initialized with themselves. Note this option can only be used with the -Wuninitialized option.
For example, GCC warns about i being uninitialized in the following snippet only when -Winit-self has been specified:
int f()
{
int i = i;
return i;
}
This warning is enabled by -Wall in C++.
Based on the comments below there may be some version dependencies. Note, that clang
generates a warning for this just using -Wall
, which seems more sensible to me:
warning: variable 'x' is uninitialized when used within its own initialization [-Wuninitialized]
int x = x;
~ ^
The live example I linked above also includes a commented out clang
command line.
Also see Why is -Winit-self separate from -Wuninitialized.
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