C Switch Statement


The switch statement in C is an alternate to if-else-if ladder statement which allows us to execute multiple operations for the different possibles values of a single variable called switch variable. Here, We can define various statements in the multiple cases for the different values of a single variable.

The syntax of switch statement in c language is given below:



  1. switch(expression){    
  2. case value1:    
  3.  //code to be executed;    
  4.  break;  //optional  
  5. case value2:    
  6.  //code to be executed;    
  7.  break;  //optional  
  8. ......    
  9.     
  10. default:     
  11.  code to be executed if all cases are not matched;    
  12. }  


Rules for switch statement in C language


1) The switch expression must be of an integer or character type.

2) The case value must be an integer or character constant.

3) The case value can be used only inside the switch statement.

4) The break statement in switch case is not must. It is optional. If there is no break statement found in the case, all the cases will be executed present after the matched case. It is known asfall through the state of C switch statement.

Let's try to understand it by the examples. We are assuming that there are following variables.



  1. int x,y,z;  
  2. char a,b;  
  3. float f; 


Switch case example 2



  1. #include <stdio.h>  
  2. int main()  
  3. {  
  4.     int x = 10, y = 5;   
  5.     switch(x>y && x+y>0)  
  6.     {  
  7.         case 1:   
  8.         printf("hi");  
  9.         break;   
  10.         case 0:   
  11.         printf("bye");  
  12.         break;  
  13.         default:   
  14.         printf(" Hello bye ");  
  15.     }   
  16.           
  17. }  

Output

hi	




Jay Kakadiya

Jay Kakadiya Creator

I am a computer field, & i am Web developer.

Suggested Creators

Jay Kakadiya