0 votes
in C Plus Plus by
Is a default case necessary in a switch statement?

1 Answer

0 votes
by

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:

switch (char_code)
{
     case '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:

...
     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:

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;
     }
}

Related questions

0 votes
asked Jan 6 in C Plus Plus by GeorgeBell
0 votes
asked Jan 12 in C Plus Plus by GeorgeBell
...