Switch Statement in C

C Switch Statement

  • The switch statement in C language is used to execute the code from multiple conditions
  • It is like if else-if ladder statement.
The syntax of switch statement in c language is given below:
switch(expression){    
case value1:    
 //code to be executed;    
 break;  //optional  
case value2:    
 //code to be executed;    
 break;  //optional  
......    
    
default:     
 code to be executed if all cases are not matched;    
}    

Rules for switch statement in C language

  1. The switch expression must be of integer or character type.
  2. The case value must be 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. 
  5. It is optional. 
  6. If there is no break statement found in switch case, all the cases will be executed after matching the case value. 
  7. It is known as fall through state of C switch statement.
Let's try to understand it by the examples. We are assuming there are following variables.
  1. int x,y,z;  
  2. char a,b;  
  3. float f;  

Flowchart of switch statement in C

Let's see a simple example of c language switch statement.
  1. #include<stdio.h>  
  2. #include<conio.h>  
  3. void main(){  
  4. int number=0;  
  5. clrscr();  
  6. printf("enter a number:");  
  7. scanf("%d",&number);    
  8. switch(number){  
  9. case 10:  
  10. printf("number is equals to 10");  
  11. break;  
  12. case 50:  
  13. printf("number is equal to 50");  
  14. break;  
  15. case 100:  
  16. printf("number is equal to 100");  
  17. break;  
  18. default:  
  19. printf("number is not equal to 10, 50 or 100");  
  20. }  
  21. getch();  
  22. }  

Output

enter a number:4
number is not equal to 10, 50 or 100
enter a number:50
number is equal to 50

C Switch statement is fall-through

  • In C language, switch statement is fall through, it means if you don't use break statement in switch case, all the case after matching case will be executed.
  • Let's try to understand the fall through state of switch statement by the example given below.
#include<stdio.h>  
#include<conio.h>  
void main(){  
int number=0;  
clrscr();  
printf("enter a number:");  
scanf("%d",&number);  
switch(number){  
case 10:  
printf("number is equals to 10\n");  
case 50:  
printf("number is equal to 50\n");  
case 100:  
printf("number is equal to 100\n");  
default:  
printf("number is not equal to 10, 50 or 100");  
}  
getch();  
}  

Output

enter a number:10

number is equals to 10

number is equals to 50

number is equals to 100
number is not equal to 10, 50 or 100


enter a number:50
number is equal to 50
number is equals to 100
number is not equal to 10, 50 or 100

                                                         

Post a Comment

Previous Post Next Post