What is your procedure when switching over an enum where every enumeration is covered by a case? Ideally you’d like the code to be future proof, how do you do that?
Also, what if some idiot casts an arbitrary int to the enum type? Should this possibility even be considered? Or should we assume that such an egregious error would be caught in code review?
enum Enum
{
Enum_One,
Enum_Two
};
Special make_special( Enum e )
{
switch( e )
{
case Enum_One:
return Special( /*stuff one*/ );
case Enum_Two:
return Special( /*stuff two*/ );
}
}
void do_enum( Enum e )
{
switch( e )
{
case Enum_One:
do_one();
break;
case Enum_Two:
do_two();
break;
}
}
- leave off the default case, gcc will warn you (will visual studio?)
- add a default case with a
assert(false); - add a default case that throws a catchable exception
- add a default case that throws a non-catchable exception (it may just be policy to never catch it or always rethrow).
- something better I haven’t considered
I’m especially interested in why you choose to do it they way you do.
I throw an exception. As sure as eggs are eggs, someone will pass an integer with a bad value rather than an enum value into your switch, and it’s best to fail noisily but give the program the possibility of fielding the error, which assert() does not.