I'd like to get a compiler warning or error when not all possible enum values are handled in a switch statement. Of course I can add a default case with an assert and (eventually) get an error at runtime. But I'd like to get an error at compile-time.
I'm not sure if this is possible at all with C++, but maybe someone knows a trick...
Edit:
Using -Wswitch
seems to be the solution for GCC. Is there something similar for VS2010? (I'm not using GCC).
Edit2: Ok, I found the solution for VC++ (VS2010):
Enabling warning C4062
produces a warning when a value is missing und no default case is provided.
Enabling warning C4061
produces a warning when a value is missing, even if a default case is provided.
You haven't mentioned which compiler you're using. If you're using GCC, you can get that for free simply by enabling -Wswitch
(which is automatically enabled by -Wall
).
AFAIK there's no conventional way to achieve what you want with MSVC. There're tricks to do similar things, but they involve either a sophisticated template voodoo, or really fierce macros riddles.
For example, instead of defining your enum in a conventional way do the following:
#define MyEnumEntries(m) \
m(A, 1) \
m(B, 2) \
m(C, 3) \
enum Abc {
// the following will expand into your enum values definitions
# define M_Decl(name, value) name = value,
MyEnumEntries(M_Decl)
};
Now, your switch can be rewritten into this:
Abc a = A;
switch( a )
{
#define M_Goto(name, value) \
case value:
goto label_##name;
MyEnumEntries(M_Goto)
case label_A:
// TODO
break;
case label_B:
// TODO
break;
}
The above will not compile if you won't add the switch entry label_...
for all the enum values.
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