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.
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...
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With