Switch case with logical operator in C

39,573

Solution 1

case 1||2:

Becomes true. so it becomes case 1: but the passed value is 2. so default case executed. After that your printf("I thought somebody"); executed.

Solution 2

do this:

switch(suite){
  case 1:/*fall through*/
  case 2: 
    printf("Hi");
...
}

This will be a lot cleaner way to do that. The expression 1||2 evaluates to 1, since suite was 2, it will neither match 1 nor 3, and jump to default case.

Solution 3

case 1||2:

Results in

case 1:

because 1 || 2 evaluates to 1 (and remember; only constant integral expressions are allowed in case statements, so you cannot check for multiple values in one case).

You want to use:

case 1:
  // fallthrough
case 2:
Share:
39,573
Admin
Author by

Admin

Updated on October 09, 2021

Comments

  • Admin
    Admin over 2 years

    I am new to C and need help. My code is the following.

     #include<stdio.h>  
     #include<conio.h>  
     void main()
     {
    
      int suite=2;  
    
      switch(suite)
         {           
          case 1||2:
          printf("hi");
    
          case 3:
          printf("byee");
    
          default:
          printf("hello");
         }
    
      printf("I thought somebody");
      getche();
      }
    

    I am working in Turbo C and the output is helloI thought somebody. There's no error message.

    Please, let me know how this is working.