C Switch Statement

The switch statement in C language is used to execute the code from multiple conditions.It is same like if else-if ladder statement.

switch statement work with byte, short, char and int primitive data type, it also works with enumerated types and string.

	case value1: 
	//code to be executed; 
	break; //optional
	case value2: 

	//code to be executed; 
	break; //optional

	code to be executed if all cases are not matched; 


Rules for switch statement in C

  • The switch expression must be of integer or character type.
  • With switch statement use only byte, short, int, char data type.
  • With switch statement not use float data type.
  • You can use any number of case statements within a switch.
  • The case value can be used only inside the switch statement.
  • Value for a case must be same as the variable in switch.
  • 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;
      byte y;
      short z;                 
Valid Switch Invalid Switch Valid Case Invalid 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;

void main(){ 
int number=0; 

printf("enter a number:"); 
case 10: 
printf("number is equals to 10"); 
case 50: 
printf("number is equal to 50"); 
case 100: 
printf("number is equal to 100"); 
printf("number is not equal to 10, 50 or 100"); 


Output of this programme

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