C switch case invalid ways



Illegal way of using Switch Statement in C Programming ?

We have collected all the scenarios of switch that results into compile error. We call them as illegal use of switch case statement, following are the illegal ways of switch case statement in C Programming language :

  1. Floating point values are not allowed as Case Label.
  2. Case Labels Should be Unique.
  3. Variables are not allowed in switch case.
  4. Comparison operators are not at all accepted.
  5. All statements inside switch must be wrapped inside any of the case.

Case 1 : Floating Case Not Allowed !!!

switch case label allows only integer value inside case label. Floating points are not at all accepted inside switch case.

i = 1.5
switch ( i )
{
   case 1.3:
             printf ("Case 1.3");
             break;
   case 1.4:
             printf ("Case 1.4");
             break;
   case 1.5:
             printf ("Case 1.5");
             break;
    default :
             printf ("Default Case ");
}

Case 2 : Case Labels Should be Unique

i = 1;
switch ( i )
{
case 1:
    printf ("Case 1");
    break;
case 1:
    printf ("Case 2");
    break;
case 3:
    printf ("Case 3");
    break;
default :
    printf ("Default Case ");
}

Case 3 : Case Labels Should not Contain any Variable

Case label must be constant value.

i = 1;
switch ( i )
{
case 1:
    printf ("Case 1");
    break;
case i + i :
    printf ("Case 2");
    break;
case 3:
    printf ("Case 3");
    break;
default :
    printf ("Default Case ");
}

Case 4 : All Cases must wrapped in any of the case

( Generally Compiler won’t show Error Message but It will neglect statement which does not belongs to any case)

i = 1;
switch(i)
{
printf ( "Hi") // It does not belongs to any case
case 1:
      printf("Case 1");
      break;
case 2:
      printf("Case 2");
      break;
case 3:
      printf("Case 3");
      break;
default :
      printf("Default Case ");
}

Output :

Case 1

Case 5 : Comparison Not allowed

i = 1;
switch(i)
{
case i>1:
     printf ("Case 3");
     break;
default :
     printf ("Default Case ");
}