Use of variable in switch case



In this tricky questions, we are using the variable in switch case statement. Tutorial will explain the behaviour of program when we use variable in switch case statement

Use of variable in switch case

void main()
{
 int choice = 1 ;
 int a = 2;
 switch(choice)
 {
  case 1 :
        printf("I am in case 1.1");
        break;
  case 1 :
        printf("I am in case 1.2");
        break;
  case a :
        printf("I am in case A");
        break;
 }
}

Options for above question :

  1. Variables are not allowed in Case Labels
  2. Default is absent
  3. No continue statement in Statement
  4. All Cases in switch are not unique

Explanation

Above program will throw an error because these following two reasons -

  1. Variables are not allowed in case labels
  2. All cases in switch are not unique

Use of Variable in switch case

We will discuss these reasons one by one -

Reason 1 : Variables not allowed

Consider that you have used variable in switch case as switch label

case a :
        printf("I am in case A");
        break;

We know that when we use variable name then the value of variable can be modified at any moment of time. Suppose at particular time value of the variable is 2 then the case inside switch become case 2 and suppose the value of variable becomes 3 then the case becomes case 3

In short the value of variable may alter the case definition so it is recommanded not to use variable in switch case statement

Reason 1 : Variables not allowed

case 1 :
        printf("I am in case 1.1");
        break;
case 1 :
        printf("I am in case 1.2");
        break;

Consider the above program where we have two same cases so it may confuse compiler which case to execute so it will throw an compile error in c program

Recommended Article : Rules of using switch case statement