[Bug c/87983] Feature: Add a warning when case labels from a different enum than the one in switch(EXPR) are used

avarab at gmail dot com gcc-bugzilla@gcc.gnu.org
Thu Jan 20 10:40:01 GMT 2022


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

--- Comment #4 from Ævar Arnfjörð Bjarmason <avarab at gmail dot com> ---
(In reply to Eric Gallager from comment #3)
> Is the expectation that this would come from -Wswitch, -Wswitch-enum,
> -Wenum-compare, -Wenum-conversion, or some new flag?

I think a new flag would be best. The clang compiler has a C++-only
-Wenum-compare-switch flag which will warn about this.

Here's a better and updated testcase showing how it works:

```
#include <stdio.h>

enum enum_x { A, B };
enum enum_y { C, D };

int main(void)
{   
    enum enum_y y = C;
    switch (y) {
      case A: /* Should warn: switch() on C instead of A */
        puts("A");
        break;
      case D:
        puts("B");
        break;
    }
}
```

And a one-liner showing how gcc, g++, clang and clang++ handle it:

```
$ for cc in gcc g++ clang clang++; do echo $cc: && $cc -Wswitch -Wswitch-enum
-Wenum-compare -o test test.c; ./test; done
gcc:
A
g++:
A
clang:
A
clang++:
clang: warning: treating 'c' input as 'c++' when in C++ mode, this behavior is
deprecated [-Wdeprecated]
test.c:10:12: warning: comparison of different enumeration types in switch
statement ('enum enum_y' and 'enum_x') [-Wenum-compare-switch]
      case A: /* Should warn: switch() on C instead of A */
           ^
1 warning generated.
A
```

(This is with a local GCC 10.* and LLVM 13.*, on a Debian box). Documentation
for the Clang warning:
https://clang.llvm.org/docs/DiagnosticsReference.html#wenum-compare-switch


More information about the Gcc-bugs mailing list