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. It is optional. If there is no break statement found in switch case, all the cases will be executed after matching the case value. 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.

int x,y,z;

char a,b;

float f;

Valid SwitchInvalid SwitchValid CaseInvalid Case
switch(x)switch(f)case 3;case 2.5;
switch(x>y)switch(x+2.5)case 'a';case x;
switch(a+b-2)case 1+2;case x+2;
switch(func(x,y))case 'x'>'y';case 1,2,3;

Let's see a simple example of c language switch statement.

C Switch Statement



#include<stdio.h>
int main(){    
int number=0;     
printf("enter a number:");    
scanf("%d",&number);    
switch(number){    
case 1:    
printf("number is equals to 1");    
break;    
case 5:    
printf("number is equal to 5");    
break;    
case 10:    
printf("number is equal to 10");    
break;    
default:    
printf("number is not equal to 1, 5 or 10");    
}    
return 0;  
}    



Output

enter a number:4

number is not equal to 1, 5 or 10

enter a number:5

number is equal to 5

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>  
int main(){    
int number=0;    
  
printf("enter a number:");  
scanf("%d",&number);  
  
switch(number){  
case 10:  
printf("number is equals to 10\n");  
case 20:  
printf("number is equal to 20\n");  
case 200:  
printf("number is equal to 200\n");  
default:  
printf("number is not equal to 10, 20 or 200");  
}  
return 0;  
}   



Output

enter a number:10

number is equals to 10

number is equals to 80

number is equals to 200

number is not equal to 10, 20 or 200

enter a number:50

number is equal to 20

number is equals to 200

number is not equal to 10, 20 or 200




Instagram