今天在看代码的时候发现了一个类似如下的结构: switch(error) { case ENUM_0: case ENUM_1: printf("case 0 and 1\n"); case ENUM_2: printf("case 2\n"); break; } 就有点疑惑,若 error 取值为 ENUM_0 或 ENUM_1 时,printf("case 0 and 1\n"); 这句肯定是执行了的。但不确定会不会走到下面的 case 里面去?
后面为了验证这个小问题,在VC里面编了个例子试了一把,证实确实执行到了 case 2 的分支里面去了。并且执行到 break 时才跳出。 [cpp] #include <stdio.h>
int main(void) { char ch = 0;
switch(ch) { case 0: case 1: printf("case 0 excute\n"); case 2: printf("case 2 excute\n"); break; }
return 0; } 总结,case 分支下面的语句会一直执行到 break 或 return 时跳出。
|