Relational operators in switch case



In this tutorial we will be learning how to tackle c program if we have relational operators in switch case.

Relational operators in switch case

void main()
{
   int choice = 10 ;
   switch(choice) 
   {
    case <10:
         printf("Less than 10");
         break;

    case =10:
         printf("Equal to 10");
         break;

    case >10:
         printf("Greater than 10");
         break;
   }
}

Options :

  1. Yes
  2. No

Explanation

In C programming when you use relational operator in an expression then it will return you two results either true or false i.e 0 or 1.

Relational operators in switch case

Consider the below program which is expanded version after evaluating expression

void main()
{
   int choice = 10 ;
   switch(choice) 
   {
    case 0:
         printf("Less than 10");
         break;

    case 1:
         printf("Equal to 10");
         break;

    case 0:
         printf("Greater than 10");
         break;
   }
}

You will find the above expansion because here choice = 10 so only 2nd condition will be evaluated to be true so all the remaining cases will be having label 0.

Recommended Article : Switch Case statement in C | Rules of using switch case

In this case all other conditions will be having same switch case label so it will throw compile time error. So C does not allow us to use relational operators in switch case