Switch –case statement generally to check the value of an integer with different discrete possibilities. Let us plan to have a menu driven program where there is a variable called int menu_selection, which can have values like 0, 1, 2, 3, -1, etc as user selection value. Now say 0 means new student addition, 1 means edit record, 2 means display record and -1 means exit to previous menu. Here we trying to implement this with if-else-if statement.

if (menu_selection == -1) {

   printf ("Exitting.\n");

} else if (menu_selection == 0) {

  add_record ();
 
} else if (menu_selection == 1) {

  edit_record ();
  
} else if (menu_selection == 2) {

  display_record ();
  
} else if (menu_selection == 3) {

  delete_record ();
  
} else {

  printf ("Invalid selection.\n");
  
}

This type of comparison with discrete values is best suited for a switch case. Now we will re-write the above logic in a more managed way. Here point to remember is if-else-if statements are used mainly to check integer range values and switch is used to check distinct values.

switch (menu_selection) {
  
  case -1:
  printf ("Exitting.\n");
  break;
  
  case 0
  add_record ();
  break;
  
  case 1
  edit_record ();
  break;
  
  case 2
  display_record ();
  break;
  
  case 3
  delete_record ();
  break;
  
  default:
  printf ("Invalid selection.\n");
}
Here we have a default case which is similar to that last else statement. Control generally goes to this case when there is no match found in all cases. It is always recommended to put a break statement at the end of each case to send the control to the end of switch.

switch (<variable>) {
  
  case <value>:
  <statement (s)>
  break;
  
  case <value>:
  <statement (s)>
  break;
  
  ...
  

  default:
  <statement (s)>
}


switch (<variable>) {
  
  case <value>{
    <statement (s)>
    break;
  }
  
  case <value>{
    <statement (s)>
    break;
  }
  
  ...
  

  default: {
    <statement (s)>
  }
}

Please note: Placing a break at the end of a case is optional. Not putting break in one case causes control to go to the next case block unconditionally. In our example we can remove the break after edit_record(). This will take the control to go to display_record (); after an edit.

switch (menu_selection) {
  
  case -1:
  printf ("Exitting.\n");
  break;
  
  case 0
  add_record ();
  break;
  
  case 1
  edit_record (); /* No break */
  
  case 2
  display_record ();
  break;
  
  case 3
  delete_record ();
  break;
  
  default:
  printf ("Invalid selection.\n");
}

Also note there is no break at the end of default case. Default case is the last case block thus control is supposed to go to the end of switch and hence break is not required here. Even if putting a break will not cause any error either.

About our authors: Team EQA

You have viewed 1 page out of 252. Your C learning is 0.00% complete. Login to check your learning progress.

#