2

可能重复:
达夫的设备是如何工作的?

我试图了解这是如何工作的。任何帮助,将不胜感激。

#include<stdio.h>

void duff(int count)
  {
      int n=(count+7)/8;
      printf("n=%d  count =%d\n",n,count%8);
      switch(count%8){
      case 0: do{ printf("case 0\n");
      case 7:  printf("case 7\n");
      case 6: printf("case 6\n");
      case 5: printf("case 5\n");
      case 4: printf("case 4\n");
      case 3: printf("case 3\n");
      case 2: printf("case 2\n");
      case 1: printf("case 1\n");
              }while( --n >0);
      }
  }

main(){
int count;
scanf("%d",&count);
duff(count);

}

基本上,如果 switch case 评估为 case 语句 2,则不会执行 while 的 do 语句。但是我运行了这个程序,它给了我输出,但无法解释:
输出:

3
n=1 计数 =3
案例 3
案例 2
案例 1

4

3 回答 3

3

这被称为 duff 设备,用于代码优化技术以减少分支指令。它起作用的原因是默认情况下没有中断的 case 语句会进入下一个 case,所以当你遇到 case 3 时,你会继续进入 case 2 和 case 1。

于 2012-03-07T03:07:32.417 回答
1

thedocase“语句”本质上只是“goto 标签”。他们不添加任何实际代码。他们只是告诉whileswitch(分别)跳到哪里。换句话说,没有用于do(不)执行的代码。

(也就是说,C 的语法允许cases存在于 的子代中switch,而不是直接存在于 a 的子代中,这有点显着/奇怪switch。)

于 2012-03-07T03:08:59.460 回答
0

案件之间没有break陈述,因此案件失败。因此 n=3 导致case 3: case 2:andcase 1:被执行。

于 2012-03-07T03:08:11.727 回答