Is there a way to not warn about the "COUNT" enumeration constants that are missing when switching to gcc?

If a switch with an argument of type enumeration skips some constants and does not have a default branch, the gcc -Wswitch option raises a warning similar to

 warning: enumeration value 'WHATEVER' not handled in switch 

However, many of our switches are similar to:

 enum foo { FOO_ONE, FOO_TWO, FOO_COUNT }; 

where FOO_COUNT is never displayed as a value, but is used to determine the number of values ​​that are defined and can be displayed in a variable. Since we are indexing an array with an enumeration value or bit packing, and you need to check that it will match or something like that. Thus, an enumeration that processes all values ​​should not include this constant. Is there a way to keep this warning, but to 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 .

+6
source share
3 answers

I personally prefer a different approach: generate enum through a macro to set up an account.

 GENERATE_ENUM(foo, (FOO_ONE)(FOO_TWO)) 

will produce:

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

Thus, my listing is free.

A macro can also be adapted to create other useful values, such as (in the case of a disconnected enumeration) an array of all values ​​(in order), which can be useful for automating iteration or checking for existence, etc.

+3
source

If you already know which of your switch handles all the values, you can add the default: keyword to them, but at the same time it will capture all other values ​​that are not specified in your switch-case , so you will not be warned. even if you forget, for example, case FOO_ONE:

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

You can also combine it with a macro so that you can "enable" warnings from one point in 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 can "disable" warnings for any type of switch , and you will not be forced to update the switch code if you change your enum FOO_COUNT or if you have different names for your account variables.

Otherwise, you send David Rodriguez - dribeas post

+2
source

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

 switch (foo) { ... case FOO_COUNT: //empty } 
+1
source

Source: https://habr.com/ru/post/923672/


All Articles