I have a piece of code of the following form:
typedef enum {A=1,B} EnumType;
int foo (EnumType x)
{
int r;
switch (x) {
case A:
r = 1;
break;
case B:
r = 2;
break;
/*
default:
r = -1;
break;
*/
}
return r;
}
I compile with GCC 6.3.0 and receive a warning:
$ gcc --version
gcc (MacPorts gcc6 6.3.0_2) 6.3.0
Copyright (C) 2016 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.
$ gcc -c -Wall -O1 test.c
test.c: In function 'foo':
test.c:20:10: warning: 'r' may be used uninitialized in this function [-Wmaybe-uninitialized]
return r;
^
The code seems safe to me, and indeed there is some discussion of GCC producing false positives with this warning.
Is this a spurious warning?
More relevant information:
- Adding the commented-out
default:block resolves the warning - The warning does not appear with
-O0
This warning is entirely correct, because an
enumtype doesn't restrict the possible values to the members defined in thisenum-- it can instead hold any value of the underlying integer type. So without adefaultbranch in your switch, you could indeed useruninitialized with the code you show.I can reproduce the warning missing with
gccand-O0with the exact code shown in the question, so this looks to me like a bug ingcc. The warning should be given regardless of the optimization level.