最近看berkerly DB的源代码,在hash函数的hash4中一段代码让我很困惑,将其简化如下:
/*ctest.c*/
void testSwitch(int sw){
int loop = 3;
switch(sw){
case 0:
do{
printf("case 0:%d/n",loop);
case 7:
printf("case 7:%d/n",loop);
case 6:
printf("case 6:%d/n",loop);
case 5:
printf("case 5:%d/n",loop);
case 4:
printf("case 4:%d/n",loop);
case 3:
printf("case 3:%d/n",loop);
case 2:
printf("case 2:%d/n",loop);
case 1:
printf("case 1:%d/n",loop);
}while(--loop);
}
}
int main()
{
testSwitch(4);
return 0;
}
程序的输出为
case 4:3
case 3:3
case 2:3
case 1:3
case 0:2
case 7:2
case 6:2
case 5:2
case 4:2
case 3:2
case 2:2
case 1:2
case 0:1
case 7:1
case 6:1
case 5:1
case 4:1
case 3:1
case 2:1
case 1:1
这表明switch语句确实就是使用了goto跳转,所以可以将case植入到其它语句中,如本例中的while语句;case本身就是一个标签;
分析完这段代码,我翻看了以前搞到手的C puzzles,发现其中已经收录了这一puzzle,以前嫌麻烦,懒的看,需要用时才发现。学习源代码!
一个小程序重新透视C语言Switch语句
最新推荐文章于 2022-02-01 15:21:06 发布