Technically, no you don't, because you've covered all possible cases with your switch statement.
However, I always find it useful to include an assertion/exception in the default anyway. Consider the following scenario:
// V1.0.0: Initial version.
int num = rand()%3;
switch (num)
{
case 0: methodOne();
break;
case 1: methodTwo();
break;
case 2: methodThree();
break;
}
Later...
// V1.0.0: Initial version.
// V1.0.1: Added a fourth method.
int num = rand()%4;
switch (num)
{
case 0: methodOne();
break;
case 1: methodTwo();
break;
case 2: methodThree();
break;
}
In this scenario, developer #2 updated the rand
modulus, but didn't actually add the case to handle num == 4
. Without the default
, you're going to silently fail, and that could cause all kinds of badness that could be very hard to debug. A more maintainable solution might be:
// V1.0.0: Initial version.
// V1.0.1: Added a fourth method.
int num = rand()%4;
switch (num)
{
case 0: methodOne();
break;
case 1: methodTwo();
break;
case 2: methodThree();
break;
default:
assert(false);
throw InvalidNumException("BUG: Method has not been specified for value of num");
}
When debugging, this would stop the debugger at the assert, and if (god forbid) the missing case
makes it all the way to production, you'll get an exception thrown, rather than just running off and doing stuff that shouldn't happen.
EDIT:
I think including a catch-all is a good addition to a defensive programming style. It guarantees that you'll get a useful outcome if you miss a case
statement (even if that useful outcome is to cause the program to crash).
EDIT 2:
As Andre Kostur mentioned in a comment to this answer, some compilers will emit warnings if you switch on an enum and forget to handle a case
, which is a good reason to not include a default
case for an enum switch statement. Refer to Phresnel's answer for more information about that.