switch statement in c


  • A switch statement allows a variable to be tested for equality against a list of values. Each value is called a case, and the variable being switched on is checked for each switch case.
  • The switch statement is a multi-way branch statement. In the program, if there is a possibility to make a choice from a number of options, then structured selection is useful.
  • It requires only one argument of any data type, which is checked with number of case options.
  • The statement evaluates expression and then looks for its value among the case constants.
  • If the value matches with the case constant, this particular case statement is executed. If not, default is executed.
  • Here switch, case and default are reserved keywords. Every case statement terminates with ‘:’.
  • The break statement is used to exit from current case structure. The switch()statement is useful for writing menu driven program.

    Syntax:

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

Flow Diagram:

    switch statement in c

    Example:

    #include <stdio.h>
    int main()
    {
         int num=2;
         switch(num+2)
         {
             case 1:
               printf("Case1: Value is: %d", num);
             case 2:
               printf("Case1: Value is: %d", num);
             case 3:
               printf("Case1: Value is: %d", num);
             default:
               printf("Default: Value is: %d", num);
        }
        return 0;
    }
    
    

    Output:

    Default: value is: 2