达夫设备(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;
}