達(dá)夫設(shè)備(Duff's Device)
C語言中著名的"達(dá)夫設(shè)備"利用case語句在其匹配switch語句子塊中也是合法的這一事實(shí)。Tom Duff利用這個方法優(yōu)化輸出回路:
switch (count % 8) {
case 0: do { *to = *from++;
case 7: *to = *from++;
case 6: *to = *from++;
case 5: *to = *from++;
case 4: *to = *from++;
case 3: *to = *from++;
case 2: *to = *from++;
case 1: *to = *from++;
} while ((count -= 8) > 0);
}
我們可以稍加變動將它應(yīng)用到協(xié)同程序技巧上。我們可以用switch語句本身執(zhí)行跳轉(zhuǎn),而不是用它來確定跳到哪里去執(zhí)行。
int function(void) {
static int i, state = 0;
switch (state) {
case 0: /* start of function */
for (i = 0; i < 10; i++) {
state = 1; /* so we will come back to "case 1" */
return i;
case 1:; /* resume control straight after the return */
}
}
}
現(xiàn)在這看起來更理想了。我們現(xiàn)在需要做的只是構(gòu)造一些精確宏,并且可以把細(xì)節(jié)隱藏到這些似是而非的定義里:
#define crBegin static int state=0; switch(state) { case 0:
#define crReturn(i,x) do { state=i; return x; case i:; } while (0)
#define crFinish }
int function(void) {
static int i;
crBegin;
for (i = 0; i < 10; i++)
crReturn(1, i);
crFinish;
}