Multiple parameters in switch case label : Switch case MCQ



In this tutorial we will be learning new way of using switch case statements. In this example we will be using Multiple parameters in switch case label in C Programming

Multiple parameters in switch case label

void main()
{
 int choice = 2 ;
 switch(choice)
 {
  case 1,2,1 :
        printf("Case 1,2,1");
        break;

  case 1,3,2 :
        printf("Case 1,3,2");
        break;

  case 4,5,3 :
        printf("Case 4,5,3");
        break;
 }
}

Output :

Case 1,3,2

Explanation

In this program we have all the cases separated with the comma, like –

case 1,2,1 :

In order to tackle such kind of statement we need to understand the Operator precedence and associativity table from chapter C programming operators.

Role of comma operator

Comma operator is usually used for separating things. See different usages of comma operators.

Comma operator returns rightmost operand and it goes on executing from left to right, so in this situation case 1,2,1 will execute like –

case 1,2,1 = Execute from L -> R
           = case 1,2,1   // Return rightmost operand from 1st & 2nd
           = case 2,1     // Return rightmost operand from 2nd & 3rd
           = case 1

In short –

Case Explanation
case 1,2,1 It would return case 1
case 1,2,2 It would return case 2
case 1,2,3 It would return case 3
case 3,4,4 It would return case 4
case 5,5,5 It would return case 4