No, but it is not a bad idea to put default statements in switch statements for error- or logic-checking purposes. For instance, the following switch statement is perfectly normal:
1 2 3 4 5 6 7 8 | switch (char_code) { ase ‘Y’: case ‘y’: printf (“You answered YES!\n”); break ; case ‘N’: case ‘n’: printf (“You answered NO!\n”); break ; } |
Consider, however, what would happen if an unknown character code were passed to this switch statement. The program would not print anything. It would be a good idea, therefore, to insert a default case where this condition would be taken care of:
1 2 3 4 | ... default : printf (“Unknown response: %d\n”, char_code); break ; ... |
Additionally, default cases come in handy for logic checking. For instance, if your switch statement handled a fixed number of conditions and you considered any value outside those conditions to be a logic error, you could insert a default case which would flag that condition. Consider the following example:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 | void move_cursor( int direction) { switch (direction) { case UP: cursor_up(); break ; case DOWN: cursor_down(); break ; case LEFT: cursor_left(); break ; case RIGHT: cursor_right(); break ; default : printf (“Logic error on line number %ld!!!\n”,__LINE__); break ; } } |