奇怪的开关在c中的行为

时间:2014-09-07 13:29:17

标签: c switch-statement

我希望下面的代码在用户输入ok1时打印3,否则打印why
为什么当用户输入3时,程序会打印why

#include <stdio.h>
#include <conio.h>

int main(void){
    int i;
    clrscr();
    scanf("%d", &i);
    switch(i){
        case (1||3):
            printf("ok\n");
            break;
        default: 
            printf("why\n");
    }
    getch();
    return 0;
}

4 个答案:

答案 0 :(得分:4)

case(1||3):

不行。如果你想说“1或3”,请写:

case 1 :
case 3 :
    printf("ok");
    break;

如果案例之间没有break,则它们会从一个案例流向另一个案例。在调试器中试试。

答案 1 :(得分:4)

表达

1||3

具有常数值1.运算符||是根据C标准

的逻辑OR运算符
  

3 ||如果任一操作数进行比较,则运算符将产生1   不等于0 ;否则,它产生0.结果的类型为int。

因此,如果输入1,则将执行案例标签下的代码。否则,将执行默认标签下的代码。

实际上你的switch语句看起来像是

   switch(i)
         {
              case 1:
                            printf("ok");
                            break;
             default: 
                           printf("why");
          }

表达式1 || 3将在编译时计算,编译器将生成与标签

对应的代码
case 1:

所有案例标签表达式在编译时进行评估,而不是编译器使用其结果的表达式。

要获得您想要的结果,您应该添加一个案例标签或将switch语句替换为if-else语句。例如

   switch(i)
         {
              case 1:
              case 3:
                            printf("ok");
                            break;
             default: 
                           printf("why");
          }

   if( i == 1 || i == 3 )
   {
       printf("ok");
   }
   else
   {
        printf("why");
   }

答案 2 :(得分:2)

您想学习以下流量控制范例:

switch(i)
{
    case (1):
    case (3):
        printf("ok");
        break;
    default: 
        printf("why");
}

其中1或3将在休息之前落空。

1 || 3 =&gt; true ...通常为0x1

答案 3 :(得分:0)

又一个解决方案:

printf( (i==1||i==3)?"ok":"why" );