This question already has an answer here:
Once again a stupid uninitialized variable error in How to fix this segmentation error in a sequence inverting program?.
So I was going to repeat the "please use -Wall
flags" comment, but when I tested the code against warnings, I found no warnings reported to my great surprise.
So I trimmed it down to this below (this code makes no sense for execution purposes but it illustrates what I want to show):
#include <stdio.h>
int main()
{
int i,len=12;
/* printf("%d\n",i); */
while(i!=len-1)
{
i++;
len--;
}
return 0;
}
when compiling it using gcc
4.7.3 and 6.2.1 using
gcc -Wall -Wextra -pedantic
I get no warnings, whereas i
is blatantly not initialized before using in the while
loop.
Now if I uncomment the printf
statement I get:
warning: 'i' is used uninitialized in this function [-Wuninitialized]
So why is the warning issued when passing i
to printf
but not in the while
test?
(It's different of gcc failing to warn of uninitialized variable because in my case, there's are no branches)
(Sounds like a bug, but it's so trivial that I wonder if I'm not missing something huge.)
It's hard to say it's a bug, because
gcc
mixes up code for optimization and for creating warnings, which is even documented for this particular warning:(from GCC docs Options to Request or Suppress Warnings, emphasis mine)
You found an IMHO very silly case here. Try
-O1
and you'll get an unexpected warning:So,
gcc
still misses the first uninitialized use, but finds the second one! Try-O0
or-O2
and the warning is again gone...You could still try to file a bug about this. Note
clang
gets it right: