15

I recently upgraded to the new compiler Clang LLVM 4.0 and its nice. Is just in this case it is showing me an ugly warning for some old legacy code:

Warning: case value not in enumerated type 'SomeConstants' (aka 'enum SomeConstants') [-Wswitch]

switch (var) {
    case kConstant: case 3: case 4: case 8: case 35: //WARNING HERE :(
    // do my thing here
    break;
    case kOtherConstant:
    // do another thing here
    break;
    default:
    break;
}

var could be one of the values defined in the enum something like this:

typedef enum SomeConstants {
    kConstant,
    kOtherConstant,
};

and as you see 2, 4, 8, 35 are not defined (that is why the compiler is complining), but in reality they happen (this is one the obscure parts of this closed source library I am using).

Is there a way I can somehow modify my switch code so I don't get the harmless but annoying warning? Right now I am silencing it using:

switch (var) {
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wswitch"
    case kConstant: case 3: case 4: case 8: case 35:
#pragma GCC diagnostic pop
    ...

I wonder if there is a more elegant way of solving this.

Community
  • 1
  • 1
nacho4d
  • 43,720
  • 45
  • 157
  • 240
  • these special constants seem to have a meaning for you, name them in the `enum` type – Jens Gustedt Jun 18 '12 at 06:13
  • That is actually a good idea. Although the library is closed source and it wouldn't make sense it is installed by default in all systems this source compiles in. – nacho4d Jun 18 '12 at 08:58
  • 1
    You should be aware that your code has undefined behavior if you are putting a value into an enumeration which isn't in the range of representable values of the enum. – Richard Smith Jun 26 '12 at 08:32
  • … The UB is since C++11, if I understand correctly. To get rid of it, provide a fixed underlying type, as in `enum SomeConstants : int { …`. The `: int` reclaims the classic ability to store any value. – Potatoswatter Nov 20 '15 at 14:16
  • I had a this issue recently and landed on this thread. Casting it as an (int) did resolve the warning however it only it masked the actual problem. I was switching an enum passed to the function and the error was in the signature of the calling function was set to another enum definition. This would have caused some really weird behavior that would have been difficult to diagnose at run time. Moral of the story is to very closely check the common issues or ask someone else to do it for you. More than likely it's a minor mistake but in this case it could actually make the issue worse. – Neelix May 16 '23 at 18:13

1 Answers1

34

You can cast the expression of the switch() statement to int so it doesn't/can't perform that check.

After all, it's actually being used to hold an int value, not one of the listed enumerators.

Potatoswatter
  • 134,909
  • 25
  • 265
  • 421