Synopsis: | "switch" statements shall have one and only one "default" clause. |
Language: | C |
Severity Level: | 2 |
Category: | Statement and Blocks |
Description: |
Justification Defensive programming dictates that multiple choice constructs have a guard (condition), to trap "impossible" errors. Since the default action is a "catch-all" it aids the reader to enumerate the possible special cases before the general case. Exception: If a case clause is present for each of the possible values of an enum type, a default clause is not required. Example 1 #define CCBB_THE_CHOICE 1 int trigger; trigger = 2; switch (trigger) { case CCBB_THE_CHOICE: break; } /* WRONG: Default clause is missing */ Example 2 #define CCBB_THE_CHOICE 1 int trigger; ... switch (trigger) { case CCBB_THE_CHOICE: break; default: /* RIGHT */ /* any statement */ break; } Example 3 enum Colors {Red, Blue, Green} color; color = Red; switch (color) { case Red: break; case Blue: break; case Green: break; } /* RIGHT: no default clause required because all enum values are covered. */ |