why am I not getting an “used uninitialized” warning from gcc in this trivial example? [duplicate]

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:

-Wuninitialized
Warn if an automatic variable is used without first being initialized or if a variable may be clobbered by a setjmp call.
[…]
Because these warnings depend on optimization, the exact variables or elements for which there are warnings depends on the precise optimization options and version of GCC used.

(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:

warn.c: In function ‘main’:
warn.c:13:6: warning: ‘i’ may be used uninitialized in this function [-Wmaybe-uninitialized]
     i++;
      ^

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:

warn.c:10:9: warning: variable 'i' is uninitialized when used here
      [-Wuninitialized]
  while(i!=len-1)
        ^
warn.c:6:8: note: initialize the variable 'i' to silence this warning
  int i,len=12;
       ^
        = 0
1 warning generated.

Leave a Comment