C Switch Statement with Example

C Switch Statement

  • The switch statement 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 default 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 the 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, the break statement will terminate the switch block. If none of the options matched case then ‘No color’ will be displayed.
Note: In a 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");
         }
  • The 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 much suitable.
naveed08st
 

Click Here to Leave a Comment Below 0 comments

Leave a Reply:

Select Language
Copy link
Powered by Social Snap