Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Catch mixed enums in switch

Tags:

c

enums

In some legacy code I have a lot of enums, and a huge switch cases. I would like to test that the switches have pure enum types. Nonsense example:

typedef enum EN
{
    EN_0,
    EN_1
} EN_T;

typedef enum DK
{
    DK_0,
    DK_1
} DK_T;

EN_T bar = ...
switch( bar )
{
    case EN_0:
    ...
    break;
    case DK_1: //<-- mixed type
    ...
    break;
}

I tried compiling this with gcc with -Wall -Wextra -pedantic, and get no warnings. Any ideas of how to test for this? Either as compiler warnings or dedicated test code. As both the switches and enums have 100+ members it has to be generic to some level.

Edit: Please notice I am not concerned about if this is legal c, according to the C standard.

It is bad practice, and compiler can warn about bad practice or potential errors that do not break the standard, like if( a = 1)... would always be true, perfectly legal but likely to be a mistake.

I can make the compiler warn if a switch on an enum does not contain all values of that enum a.s.o.

It is preferred if the compiler can to the work, but if a tool like lint or similar can do this I would be happy too.

like image 475
Otzen Avatar asked Jan 16 '18 08:01

Otzen


2 Answers

No, you can't restrict switch case labels to the explicit values of a particular enum. (You can in C++ out of interest from C++11).

If you are able to change the enum values so they don't intersect, that might help you a little, but only at runtime.

like image 60
Bathsheba Avatar answered Nov 08 '22 08:11

Bathsheba


From standard there is only one constraint so far case labeled statement

The expression of each case label shall be an integer constant expression and no two of the case constant expressions in the same switch statement shall have the same value after conversion.

As long as it is an integer constant expression it doesn't matter whether they belong to different enums or not. So yes you can't do what you want in C.

like image 39
user2736738 Avatar answered Nov 08 '22 09:11

user2736738