C - Understanding the switch-case structure

Introduction

Here's the skeleton:

switch(expression) 
{ 
     case value1: 
         statement(s); 
         break; 
     case value2: 
         statement(s); 
         break; 
     case value3: 
         statement(s); 
         break; 
     default: 
         statement(s); 
} 

The switch items are enclosed by a pair of curly brackets.

The structure must contain at least one case statement and the default statement.

The switch statement contains an expression in parentheses.

That expression must evaluate to a single value.

It can be a variable, a value returned from a function, or a mathematical operation.

A case statement is followed by an immediate value and then a colon.

The default item ends the switch-case structure.

It's possible to construct a switch-case structure with no break statements.

Demo

#include <stdio.h> 

int main() /*from   w  w  w . ja  va 2s.  c  o  m*/
{ 
    char choice; 

    puts("Meal Plans:"); 
    puts("A - Breakfast, Lunch, and Dinner"); 
    puts("B - Lunch and Dinner only"); 
    puts("C - Dinner only"); 
    printf("Your choice: "); 
    scanf("%c",&choice); 
    printf("You've opted for "); 
    switch(choice) 
    { 
        case 'A': 
            printf("Breakfast, "); 
        case 'B': 
            printf("Lunch and "); 
        case 'C': 
            printf("Dinner "); 
        default: 
            printf("as your meal plan.\n"); 
    } 
    return(0); 
}

Result

Related Topic