问题
Possible Duplicate:
How does Duff's device work?
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);
}
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
case 3
case 2
case 1
回答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.
回答2:
Both the do
and the case
"statements" are essentially just "goto labels". They don't add any actual code. They just tell while
and switch
(respectively) where to jump to. In other words, there is no code for the do
to (not) execute.
(That said, it is somewhat remarkable/bizarre that C's grammar allows cases
to exist in children of the switch
, rather just as direct children of a switch
.)
回答3:
There are no break
statements between the cases so the cases fall through. Therefore n=3 causes case 3:
case 2:
and case 1:
to be executed.
来源:https://stackoverflow.com/questions/9595242/c-switch-statement-with-do-while-interleaved