https://gcc.gnu.org/bugzilla/show_bug.cgi?id=98684

            Bug ID: 98684
           Summary: -Wswitch interaction with "case X ... Y" -- warns for
                    X and Y not being in the enum, but not X+1, X+2, ...
                    Y-1
           Product: gcc
           Version: unknown
            Status: UNCONFIRMED
          Severity: normal
          Priority: P3
         Component: c
          Assignee: unassigned at gcc dot gnu.org
          Reporter: pmaydell at chiark dot greenend.org.uk
  Target Milestone: ---

The gcc -Wswitch warning is documented as producing warnings for "case labels
outside the enumeration range" (among other things). The implementation of this
seems to interact oddly with the "case X ... Y" syntax for specifying that a
case covers a range of values: gcc warns if X or Y is not in the enumeration,
but doesn't warn if the other values covered by this case label (X+1, X+2, ...
Y-1) are not in the enum.

Test case:

enum myenum {
  foo = -1,
  r0_low = 0,
  r0_high = 5,
};

int z(enum myenum e) {
    switch (e) {
        case foo:
            return 42;
        case r0_low ... r0_high:
            return 0;
        case 8 ... 10:
            return 5;
    }
    /* notreached */
    return 0;
}

The generated warnings are:
<source>: In function 'z':
<source>:13:9: warning: case value '8' not in enumerated type 'enum myenum'
[-Wswitch]
   13 |         case 8 ... 10:
      |         ^~~~
<source>:13:9: warning: case value '10' not in enumerated type 'enum myenum'
[-Wswitch]

So the compiler warns about only 8 and 10, but the switch cases cover also 1,
2, 3, 4 and 9 which are not in the enum.

Tested with compiler-explorer, which at the time was:
GNU C17 (Compiler-Explorer-Build) version 11.0.0 20210106 (experimental)
(x86_64-linux-gnu)
        compiled by GNU C version 7.5.0, GMP version 6.1.0, MPFR version 3.1.4,
MPC version 1.0.3, isl version isl-0.18-GMP

https://godbolt.org/z/x88KzE

(Side note: it would be useful to have a syntax in the enum definition to say
"all values X ... Y are valid for this enum type", so as to be able to tell the
compiler that without having to write them all out.)
  • [Bug c/98684] New: -Ws... pmaydell at chiark dot greenend.org.uk via Gcc-bugs

Reply via email to