Switch case with logical operator in C

前端 未结 5 1904
借酒劲吻你
借酒劲吻你 2021-01-12 20:59

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

 #include  
 #include  
 void main()
 {

  int suite=2;  

  switch(suit         


        
相关标签:
5条回答
  • 2021-01-12 21:07

    You switch on value 2, which matches default case in switch statement, so it prints "hello" and then the last line prints "I thought somebody".

    0 讨论(0)
  • 2021-01-12 21:17

    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.

    0 讨论(0)
  • 2021-01-12 21:22
    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:
    
    0 讨论(0)
  • 2021-01-12 21:26
    case (1||2):
      printf("hi");
    

    Just put brackets and see the magic.

    In your code,the program just check the first value and goes down.Since,it doesn't find 2 afterwards it goes to default case.

    But when you specific that both terms i.e. 1 and 2 are together, using brackets, it runs as wished.

    0 讨论(0)
  • 2021-01-12 21:28
    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.

    0 讨论(0)
提交回复
热议问题