C - Making a multiple-choice selection with switch

Introduction

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

Demo

#include <stdio.h> 

int main() /*from  w w  w . ja v a  2s .c  o  m*/
{ 
     int code; 

     printf("Enter the error code (1-3): "); 
     scanf("%d",&code); 

     switch(code) 
     { 
         case 1: 
             puts("Drive Fault, not your fault."); 
             break; 
         case 2: 
             puts("Illegal format, call a lawyer."); 
             break; 
         case 3: 
             puts("Bad filename, spank it."); 
             break; 
         default: 
             puts("That's not 1, 2, or 3"); 
     } 
     return(0); 
}

Result

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