The requirement for a final default
clause is defensive programming. The clause should either take appropriate action, or contain a
suitable comment as to why no action is taken. When the switch
covers all current values of an enum
- and especially when it
doesn’t - a default
case should still be used because there is no guarantee that the enum
won’t be extended.
Note that there is a more nuanced version of this rule: S3562. Use this rule if you want to require a default
case for
every switch
even if it already handles all enumerators of an enum
. Otherwise, use S3562.
Noncompliant code example
switch (param) { // Noncompliant - default clause is missing
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
}
Compliant solution
switch (param) {
case 0:
doSomething();
break;
case 1:
doSomethingElse();
break;
default:
doDefault();
break;
}