達夫設備(Duff's Device)
C語言中著名的"達夫設備"利用case語句在其匹配switch語句子塊中也是合法的這一事實。Tom Duff利用這個方法優化輸出回路:
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);
}
我們可以稍加變動將它應用到協同程序技巧上。我們可以用switch語句本身執行跳轉,而不是用它來確定跳到哪里去執行。
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 */
}
}
}
現在這看起來更理想了。我們現在需要做的只是構造一些精確宏,并且可以把細節隱藏到這些似是而非的定義里:
#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;
}