Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there any way to not warn about "COUNT" enum constants missing from switch in gcc?

If a switch with enum-type argument misses some of the constants and does not have default branch, the gcc -Wswitch option causes a warning like

warning: enumeration value 'WHATEVER' not handled in switch

However, many our switches are like:

enum foo {
    FOO_ONE,
    FOO_TWO,
    FOO_COUNT
};

where the FOO_COUNT never appears as value, but is used to know the number of values that are defined and may appear in the variable. Because we are indexing an array with the enum value or bit-packing it and need to check it will fit or something. Thus an enum that handles all values should not include this one constant. Is there a way to keep that warning, but avoid it for such special values? I.e.

switch(foo) {
    case FOO_ONE:
        anything;
};

should give a warning, but:

switch(foo) {
    case FOO_ONE:
        anything;
    case FOO_TWO:
        anything_else;
}

should not.

like image 205
Jan Hudec Avatar asked Aug 24 '12 13:08

Jan Hudec


2 Answers

I personally prefer another approach: generating the enum through a macro to set up the count.

GENERATE_ENUM(foo, (FOO_ONE)(FOO_TWO))

will produce:

enum foo {
    FOO_ONE,
    FOO_TWO
};

inline size_t size(enum foo) { return 2; }

And thus my enum is warning free.

The macro can also be adapted to produce other useful values, such as (in the case of a discontiguous enumeration) an array of all values (in order) which may be useful to automate iteration or checking for existence, etc...

like image 182
Matthieu M. Avatar answered Sep 20 '22 22:09

Matthieu M.


If you want to still have warnings for the rest of them, the only thing I can think of is to actually create the case:

switch (foo) {
...
case FOO_COUNT: //empty
}
like image 23
David Rodríguez - dribeas Avatar answered Sep 20 '22 22:09

David Rodríguez - dribeas