Should switch statements always contain a default clause?

ID : 10289

viewed : 72

Tags : defaultswitch-statementdefault

Top 5 Answer for Should switch statements always contain a default clause?

vote vote

90

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 } 
vote vote

80

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.

vote vote

76

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;  } 
vote vote

62

I would always use a default clause, no matter what language you are working in.

Things can and do go wrong. Values will not be what you expect, and so on.

Not wanting to include a default clause implies you are confident that you know the set of possible values. If you believe you know the set of possible values then, if the value is outside this set of possible values, you'd want to be informed of it - it's certainly an error.

That's the reason why you should always use a default clause and throw an error, for example in Java:

switch (myVar) {    case 1: ......; break;    case 2: ......; break;    default: throw new RuntimeException("unreachable"); } 

There's no reason to include more information than just the "unreachable" string; if it actually happens, you're going to need to look at the source and the values of the variables etc anyway, and the exception stacktrace will include that line number, so no need to waste your time writing more text into the exception message.

vote vote

60

In my company, we write software for the Avionics and Defense market, and we always include a default statement, because ALL cases in a switch statement must be explicitly handled (even if it is just a comment saying 'Do nothing'). We cannot afford the software just to misbehave or simply crash on unexpected (or even what we think impossible) values.

It can be discussed that a default case is not always necessary, but by always requiring it, it is easily checked by our code analyzers.

Top 3 video Explaining Should switch statements always contain a default clause?

Related QUESTION?