C - Making a multiple-choice selection with switch


The switch-case structure makes decisions in a C program based on a single value.


#include <stdio.h> 

int main() //from  w  w w .  j  a  v a2  s .  c om
     int code; 

     printf("Enter the error code (1-3): "); 

         case 1: 
             puts("Drive Fault, not your fault."); 
         case 2: 
             puts("Illegal format, call a lawyer."); 
         case 3: 
             puts("Bad filename, spank it."); 
             puts("That's not 1, 2, or 3"); 


The switch-case structure starts with the switch statement.

The item it evaluates is enclosed in parentheses.

The case part of the structure is enclosed in curly brackets.

A case statement shows a single value. The value is followed by a colon.

The value specified by each case statement is compared with the item specified in the switch statement.

If the values are equal, the statements belonging to case are executed.

If not, they're skipped and the next case value is compared.

The break keyword stops program flow through the switch-case structure.

After the final comparison, the switch-case structure uses a default item.

That item's statements are executed when none of the case comparisons matches.

The default item is required in the switch-case structure.

Related Topic