关于case与break关系示例辨析
下面代码的执行结果是什么( )
#include <stdio.h>
int main() {
int x = 3;
int y = 3;
switch (x % 2) {
case 1:
switch (y)
{
case 0:
printf("first");
case 1:
printf("second");
break;
default: printf("hello");
}
case 2:
printf("third");
}
return 0;
}
A.secondthird
B.hello
C.firstsecond
D.hellothird
答案解析:
switch语句时多分支的选择语句,switch中表达式结果命中那个case,就执行该case子项,如果case子项后没有跟break语句,则继续往下执行
关于该题解析,请看以下注解:
#include <stdio.h>
int main() {
int x = 3;
int y = 3;
switch (x % 2) { // x%2的结果为1,因此执行case1
case 1:
switch (y) // y是3,因此会执行case3,而case3不存在,那只能执行default
{
case 0:
printf("first");
case 1:
printf("second");
break;
default: printf("hello"); // 打印hello,打印完之后,内部switch结束,此时外部case1结束
} // 因为外部case1之后没有添加break语句,所以继续执行case2
case 2: // 打印third
printf("third"); // 外部switch结束
}
return 0;
}
即:先在内部switch的default位置打印hello,紧接着在外部case2中打印third
因此:选择D