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.
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…