Important Points about Switch Statement

1. In switch case , we can only use integer or character data type. Other types are not allowed.

Allowed:

switch(char or int) {}

Not allowed:

switch(float/double/string){}

2. An expression provided in the switch should result in a constant value otherwise it would not be valid.

Valid expressions for switch: Constant expressions allowed

switch(6 - 2 + 283)switch(6*2+6%4)

Invalid switch expressions for switch: Variable expression not allowed

switch(ab+cd)switch(a+b+c)

3. Duplicate cases are not allowed.

 For instance below switch statement in c is illegal:

switch (expression)   { 
case 5: //... break;
case 2+3: //... break;
}

4. Order of case statements don’t matters

#include <iostream>using namespace std;int main(){    int age = 3;    switch (age) {      default: cout <<"You're not 1,2,3 or 4!n";      case 1:  cout <<"You're one.n";            break;      case 4:  cout <<"You're three or four.n";  break;      case 3:  cout <<"You're three.n";          break;      case 2:  cout <<"You're two.n";            break;    }}

OUTPUT:

You're three.

5. default statement is optional.Even if switch statement do not have a default statement, it would run without any problem.

This will run without any problems

switch (age) {  case 1:  printf("You're one.");            break;  case 2:  printf("You're two.");            break;  case 3:  printf("You're three.");  case 4:  printf("You're three or four.");  break;}

6. The variable expression are also not allowed in cases.
case i+4: is not allowed in switch, but it is valid on if-else statement.


7. The statements written above cases are never executed.

switch (age) {
age = age + 10 // This statement will never get executed case 1: printf("You're one."); break; case 2: printf("You're two."); break; case 3: printf("You're three."); case 4: printf("You're three or four."); break;}

8. If we will not use break keyword then all consecutive case statements will get executed.

Exmaple:

#include <iostream>using namespace std;int main(){   int val=3;   switch(val) {      case 1: cout<<"Case1 "<<endl;      case 2: cout<<"Case2 "<<endl;      case 3: cout<<"Case3 "<<endl;      case 4: cout<<"Case4 "<<endl;      default: cout<<"Default "<<endl;    }   return 0;}

Output:

Case3 Case4 Default 

9. Nesting of switch statements are allowed, which means you can have switch statements inside another switch. However nested switch statements should be avoided as it makes program more complex and less readable.