Er *_*ngh 6 c switch-statement or-operator
我是C的新手,需要帮助.我的代码如下.
#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();
}
Run Code Online (Sandbox Code Playgroud)
我在Turbo C工作,输出是helloI thought somebody.没有错误消息.
请让我知道这是如何工作的.
Jey*_*ram 14
case 1||2:
Run Code Online (Sandbox Code Playgroud)
成为true.所以它变成case 1:但传递的值是2.所以执行默认情况.之后你printf("I thought somebody");执行了.
做这个:
switch(suite){
case 1:/*fall through*/
case 2:
printf("Hi");
...
}
Run Code Online (Sandbox Code Playgroud)
这将是一个更清洁的方式来做到这一点.表达式1||2求值为1,因为suite它是2,它既不匹配1也不匹配3,并跳转到default大小写.