Switch in C

The control statement that allows us to make a decision from the number of choices is called a switch, or more correctly a switch-case-default, since these three keywords go together to make up the control statement. They most often appear as follows:

switch ( integer expression )
{
case constant 1 :
do this ;
case constant 2 :
do this ;
case constant 3 :
do this ;
default :
do this ;
}

 
The integer expression following the keyword switch is any C expression that will yield an integer value. It could be an integer constant like 1, 2 or 3, or an expression that evaluates to an integer. The keyword case is followed by an integer or a character constant. Each constant in each case must be different from all the others. The “do this” lines in the above form of switch represent any valid C statement.
 
What happens when we run a program containing a switch? First, the integer expression following the keyword switch is evaluated. The value it gives is then matched, one by one, against the constant values that follow the case statements. When a match is found, the program executes the statements following that case, and all subsequent case and default statements as well. If no match is found with any of the case statements, only the statements following the default are executed. Following examples will show how this control structure works.

Example

#include<stdio.h>
int main( )
{
    int i = 2 ;
    switch ( i )
    {
           case 1 :
                printf ( "I am in case 1 \n" ) ;
           case 2 :
                printf ( "I am in case 2 \n" ) ;
           case 3 :
                printf ( "I am in case 3 \n" ) ;
           default :
                printf ( "I am in default \n" ) ;
    }
    getchar();
    return 0;
}

The output is definitely not what we expected! We didn’t expect the second and third line in the above output. The program prints case 2 and 3 and the default case. Well, yes. We said the switch executes the case where a match is found and all the subsequent cases and the default as well.
 
If you want that only case 2 should get executed, it is upto you to get out of the switch then and there by using a break statement. The following example shows how this is done. Note that there is no need for a break statement after the default, since the control comes out of the switch anyway.

Example

#include<stdio.h>
int main( )
{
    int i = 2 ;
    switch ( i )
    {
           case 1 :
                printf ( "I am in case 1 \n" ) ;
                break;
           case 2 :
                printf ( "I am in case 2 \n" ) ;
                break;                
           case 3 :
                printf ( "I am in case 3 \n" ) ;
                break;                
           default :
                printf ( "I am in default \n" ) ;
    }
    getchar();
    return 0;
}