Jan Hudec
Jan Hudec

Reputation: 76386

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.

Upvotes: 6

Views: 1057

Answers (3)

Matthieu M.
Matthieu M.

Reputation: 300409

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...

Upvotes: 3

xQuare
xQuare

Reputation: 1323

If you already know which of your switchs handle all values, you can add the default: keyword to those, but at the same time, it will catch all other values that are not listed in your switch-case, so you will not be warned even if you forgot for example case FOO_ONE:.

switch(value){
    case FOO_ONE:
        break;
    default:
        break;
}

You could also combine it with a macro, so that you can "enable" the warnings from one point of your code:

#define m_ignore_switch_case_warnings default: break
//and define it like this to enable the warnings again
#define m_ignore_switch_case_warnings

switch(value){
    case FOO_ONE:
        break;

    m_ignore_switch_case_warnings;
}

You will be able to "disable" the warnings for any kind of switch and you are not forced to update your switch code in case you change your enum FOO_COUNT or if you have different names for your count variables.

Else you are reffered to David Rodríguez - dribeas's post

Upvotes: 2

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
}

Upvotes: 2

Related Questions