Switch case MCQ 10 : Shift Operators in Switch



C Programming shift operators in switch case

void main()
{
 int choice = 1 ;
 switch(choice << 1)
 {

  case 2:
        printf("Case 2");
        break;

  case 4:
        printf("Case 4");
        break;

  case 8:
        printf("Case 8");
        break;
 }
}

Explanation :

In this example we have used shift operators in switch case statements. The shift operators are of two types left shift.

int choice = 1 ;
 switch(choice << 1)
 {

In this code line we need to analyze which case label we will be executing ?

choice << 1 = Left shift Integer 1 by 1 bit
            = 0000 0000 0000 0001 << 1
            = 0000 0000 0000 0010
            = Equivalent to Integer 2
            = Case 2

In this situation, case 2 will be executed. If we shift it by 2 bits then case 4 will be executed

choice << 1 = Left shift Integer 1 by 1 bit
            = 0000 0000 0000 0001 << 2
            = 0000 0000 0000 0100
            = Equivalent to Integer 4
            = Case 4