Expression in switch case



We have already studies the expression in c programming and some basic rules of switch case statement. In this tutorial we will be learning, how expression in switch case is evaluated ?

Expression in switch case

void main()
{
 int choice = 2 ;
 switch(choice)
 {

  case 1 :
        printf("Inside case 1");
        break;

  case 7-8+3 :
        printf("Inside case 7-8+3");
        break;

  case 9/3 :
        printf("Inside case 9/3");
        break;
 }
}

Output :

Inside case 7-8+3

Explanation

Using expression in switch case is absolutely allowed in c programming. Expression should be in such a way that result of expression should be integer constant

case 7-8+3 :
    printf("Inside case 7-8+3");
    break;

In this case expression evaluation will be like this –

case 7-8+3 = case 7 - 8 + 3
           = case -1 + 3
           = case 2

So we can say that case 7-8+3 expression is equivalent to case 2

Tricky examples

Example 1 : Use of variable in switch case

In this type of example, If a variable is used to evaluate expression in switch case then it may provide result which is completely dynamic and variable dependent.

case a+1 :
    printf("Inside case 7-8+3");
    break;

The case would be –

Value of a Value of case a+1 Explanation
1 case 2 It becomes case 2 if value of variable is 1
2 case 3 It becomes case 3 if value of variable is 2
3 case 4 It becomes case 4 if value of variable is 3

We have already seen such kind of example where we have used variable in switch case statement.

Example 2 : Repeated evaluation of expression in switch case

case 7-8+3 :
     printf("Inside case 7-8+3");
     break;

case 9/3-1 :
     printf("Inside case 9/3-1");
     break;

case 7+1-6 :
     printf("Inside case 7+1-6");
     break;

In this case all the expressions are evaluated to case 2, so it is again confusing condition if we use expression in switch case.

So it is recommended to use expression in such a way that evaluation result of each expression is unique