Mastering the Switch Statement in C

The switch statement in c is useful to execute a particular task from among several tasks depending on the value of a variable or expression..

Syntax: switch(variable or expression)
        {
              case value1: statements1;
                           break;
              case value2: statements2;
                           break;
                           .
                           .
              case valuen: statementsn;
                           break;
              [default   : default_statements;]
        }

If the variable value equals value1 then statements1 will be executed. If the variable value equals value2 then statements2 will be executed, etc. If the variable value does not equal to any of the values mentioned in the ‘case’, then defualt statements will be executed. break statements in the switch is useful to come out of the block.

Example: char color='b';
         switch(color)
         {
              case 'r'=puts("red");break;
              case 'g'=puts("green");break;
              case 'b'=puts("blue");break;
              case 'w'=puts("white");break;
              default: puts("no color");
         }

In the code, the color variable value is ‘b’.Depending on color value, one of the case statements will be executed.The third case becomes true as the color value is ‘b’ and hence it displays ‘Blue’. After that, break statement will terminate the switch block. If none of the options matched case then ‘No color’ will be displayed.

Note: In switch statement, while writing the variable, it is not possible to use float, double or string type variables. We can use only int type or char type variables.

Example: double x=1.2;
         switch(x)   /* Error since x is double type */
         {
              case 1: printf("\nHellow");
              case 2: printf("\hey");
         }

Switch statement is generally used in menu driven programs. A menu represents a list of options or items. When the user wants to perform a task depending upon an option, then switch statements will be very suitable.

Naveed Tawargeri
 

Hi, I'm Naveed Tawargeri, and I'm the owner and creator of this blog. I'm a Software Developer with a passion for Programming.