In one of my first code reviews (a while back), I was told that it's good practice to include a default clause in all switch statements. I recently remembered this advice but can't remember what the justification was. It sounds fairly odd to me now.
Is there a sensible reason for always including a default statement?
Is this language dependent? I don't remember what language I was using at the time - maybe this applies to some languages and not to others?
Should a "switch" statement always include a default clause? No. It should usually include a default.
Including a default clause only makes sense if there's something for it to do, such as assert an error condition or provide a default behavior. Including one "just because" is cargo-cult programming and provides no value. It's the "switch" equivalent of saying that all "if" statements should include an "else".
Here's a trivial example of where it makes no sense:
This is the equivalent of:
As far as i see it the answer is 'default' is optional, saying a switch must always contain a default is like saying every 'if-elseif' must contain a 'else'. If there is a logic to be done by default, then the 'default' statement should be there, but otherwise the code could continue executing without doing anything.
If there is no default case in a
switch
statement, the behavior can be unpredictable if that case arises at some point of time, which was not predictable at development stage. It is a good practice to include adefault
case.Such a practice can result in a bug like NULL dereference, memory leak as well as other types of serious bugs.
For example we assume that each condition initializes a pointer. But if
default
case is supposed to arise and if we don’t initialize in this case, then there is every possibility of landing up with a null pointer exception. Hence it is suggested to use adefault
case statement, even though it may be trivial.Atleast it is not mandatory in Java. According to JLS, it says atmost one default case can be present. Which means no default case is acceptable . It at times also depends on the context that you are using the switch statement. For example in Java, the following switch block does not require default case
But in the following method which expects to return a String, default case comes handy to avoid compilation errors
though you can avoid compilation error for the above method without having default case by just having a return statement at the end, but providing default case makes it more readable.
Because MISRA C says so:
That said, I recommend against following MISRA C on this, for most software:
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
Adding:
Is just a waste of time and increases the complexity of the code for no reason.