Switch case

From Applied Science
  • Conditional structures with SWITCH and CASE:
int choice;
switch (choice) {

 case 1:  
 printf("You chose 1");  
 break;

 case 2:  
 printf("You chose 2");  
 break; 

 case 3:  
 printf("You chose 3");  
 break;

 default:  printf("You chose %d (none of the above)", choice);
}

Differences between SWITCH CASE and ELSE IF. The program's behaviour should be the same, what changes is the syntax and the performance in some cases (performance is not something to worry about in this course). The biggest difference lies in the use: SWITCH CASE doesn't use the boolean operators AND, OR and NOT. It works as a list of choices, where each choice is an integer value. It also doesn't contain the comparison operators such as "greater or equal than" and "less or equal than". SWITCH CASE is best understood when there are mutually exclusive choices.

  1. More than one case statement can match the same choice. For example: place the 'case 1:' line right above the 'case 2', this is going to make the printf() be executed in both cases;
  2. Without the 'break' command the program doesn't end the execution of the SWITCH block, continuing to the next case right below. It's a bit odd when compared to ELSE IF, but it works like that anyway. In this introduction programs that rely on such behaviour are not studied;
  3. The 'default' command works pretty much like an ELSE. It doesn't have a break command because it's always the last one to be read.
  4. Compound comparisons with more than one variable are not used with SWITCH CASE blocks. It'd be too costly to rewrite IF ELSE with compound comparisons to the SWITCH CASE format. When a range of values match one choice, it'd be insane to cover all cases one by one.