Should switch statements always contain a default clause?
No.
What if there is no default action, context matters. What if you only care to act on a few values?
Take the example of reading keypresses for a game
switch(a)
{
case 'w':
// Move Up
break;
case 's':
// Move Down
break;
case 'a':
// Move Left
break;
case 'd':
// Move Right
break;
}
Adding:
default: // Do nothing
Is just a waste of time and increases the complexity of the code for no reason.
Switch cases should almost always have a default
case.
Reasons to use a default
1.To 'catch' an unexpected value
switch(type)
{
case 1:
//something
case 2:
//something else
default:
// unknown type! based on the language,
// there should probably be some error-handling
// here, maybe an exception
}
2. To handle 'default' actions, where the cases are for special behavior.
You see this a LOT in menu-driven programs and bash shell scripts. You might also see this when a variable is declared outside the switch-case but not initialized, and each case initializes it to something different. Here the default needs to initialize it too so that down the line code that accesses the variable doesn't raise an error.
3. To show someone reading your code that you've covered that case.
variable = (variable == "value") ? 1 : 2;
switch(variable)
{
case 1:
// something
case 2:
// something else
default:
// will NOT execute because of the line preceding the switch.
}
This was an over-simplified example, but the point is that someone reading the code shouldn't wonder why variable
cannot be something other than 1 or 2.
The only case I can think of to NOT use default
is when the switch is checking something where its rather obvious every other alternative can be happily ignored
switch(keystroke)
{
case 'w':
// move up
case 'a':
// move left
case 's':
// move down
case 'd':
// move right
// no default really required here
}
NOT having the default case can actually be beneficial in some situations.
If your switch cases are enums values, by not having a default case, you can get a compiler warning if you are missing any cases. That way, if new enum values are added in the future and you forget to add cases for these values in the switch, you can find out about the problem at compile time. You should still make sure the code takes appropriate action for unhandled values, in case an invalid value was cast to the enum type. So this may work best for simple cases where you can return within the enum case rather than break.
enum SomeEnum
{
ENUM_1,
ENUM_2,
// More ENUM values may be added in future
};
int foo(SomeEnum value)
{
switch (value)
{
case ENUM_1:
return 1;
case ENUM_2:
return 2;
}
// handle invalid values here
return 0;
}