在使用C中的switch语句的疑惑 [英] Doubts in using switch statement in C
问题描述
我有一个疑问:为什么我收到输出时, I = 3
和在 I = 7
?
的main()
{
INT I;
scanf函数(%d个,&安培; I)
开关(ⅰ)
{
案例3:输出(MESSAGE3);
默认:
如果(我== 4)
的printf(消息4);
案例2:输出(消息2);
打破;
案例1:输出(消息1);
}
}
@Shubham。请原谅我,如果我是在重复你已经知道的。而且在某些方面,我有什么扩张已经@Henk指出。
在开关
语句,案例的作用
和默认
标签只确定执行应该开始。一旦第一个标签然后确定标签的其余部分没有任何意义。执行是告吹。因此,我们必须使用破
停止并退出开关
。
在您的code,如果我== 3
然后情况下3
是执行的第一线。然后情况下3
,默认
和案例2
执行后面通过破
。
如果 I
比 3
之外的任何值,那么默认
执行后跟 2的情况下
然后退出开关
。我不认为人会得到执行案例1
由于位置默认
。
I have a doubt: why am I getting outputs when i=3
and when i=7
?
main()
{
int i;
scanf("%d",&i);
switch(i)
{
case 3: printf("message3");
default:
if(i==4)
printf("message4");
case 2:printf("message2");
break;
case 1:printf("Message1");
}
}
@Shubham. Please forgive me if I am repeating what you already know. And in some ways, I am expanding what @Henk already pointed out.
In switch
statement, the role of case
and default
labels are only to determine where the execution should start. Once the first label is determined then rest of the labels have no meaning. The execution is "fall through". Therefore, we have to use break
to stop and exit the switch
.
In your code, if i == 3
then case 3
is the first line of execution. Then case 3
, default
and case 2
are executed followed by break
.
If i
is any value other than 3
then default
is executed followed by case 2
and then exit the switch
. I don't think one will ever get to execute case 1
due to the location of default
.
这篇关于在使用C中的switch语句的疑惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!