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?
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.
Depends on how the switch in particular language works, however in most languages when no case is matched, the execution falls through the switch statement without warning. Imagine you expected some set of values and handled them in switch, however you get another value in the input. Nothing happens and you don't know nothing happened. If you caught the case in default, you would know there was something wrong.
If you know that the switch statement will only ever have a strict defined set of labels or values, just do this to cover the bases, that way you will always get valid outcome.. Just put the default over the label that would programmatically/logically be the best handler for other values.
You should have a default to catch un-expected values coming in.
However, I disagree with the Adrian Smith that your error message for default should be something totally meaningless. There may be an un-handled case you didn't forsee (which is kind of the point) that your user will end up seeing and a message like "unreachable" is entirely pointless and doesn't help anyone in that situation.
Case in point, how many times have you had an utterly meaningless BSOD? Or a fatal exception @ 0x352FBB3C32342?
Should switch statements always contain a default clause ? No switch cases can exist with out default case, in switch case default case will trigger switch value
switch(x)
in this case x when not match with any other case values.I would say it depends on the language, but in C if you're switching on a enum type and you handle every possible value, you're probably better off NOT including a default case. That way, if you add an additional enum tag later and forget to add it to the switch, a competent compiler will give you a warning about the missing case.