带有do-while交错的C switch语句 [英] C switch statement with do-while interleaved

查看:105
本文介绍了带有do-while交错的C switch语句的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述


可能重复:

Duff的设备如何工作?

我正在尝试了解这是如何工作的。

I am trying to understand how this is working. Any help would be appreciated.

#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);

}

基本上,如果转换案例评估为案例陈述2,则while语句不会执行。但是我运行了这个程序,它给了我输出,但是无法解释:

输出:

Basically if the switch case evaluates to case statement 2, then the do statment of the while is never executed. But i ran this program and it gave me the output, but unable to explain:
output:

3

n = 1 count = 3

案例3

案例2

案例1

3
n=1 count =3
case 3
case 2
case 1

推荐答案

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

This is known as duff's device and is used in code optimization techniques to reduce branch instructions. The reason that it works is that by default case statements without breaks fall through to the next case so when you hit case 3, you keep going through to case 2 and case 1.

这篇关于带有do-while交错的C switch语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆