达夫设备
#include <iostream>
void fun(int i) {
switch (i) {
case 0:
for(; i <= 2; ++i) {
std::cout << "world, ";
case 2:
std::cout << "bye.\n";
return;
case 1:
std::cout << "hello ";
}
}
}
int main() {
int i = 0;
fun(i);
i = 1;
fun(i);
i = 2;
fun(i);
i = 3;
fun(i);
return 0;
}
输出
world, bye.
hello, world, bye.
bye.
switch-case语法应该是C语言中的基础,goto语法也是C语言中的基础。goto后面衔接的是label,而switch中的case也是一种label,这意味着case语句可以插入其他语句中,如for循环,这就如同电路板中的飞线,有点反直觉。

飞线
奇怪的知识增加了
当i=0时,满足case 0,然后进入for循环,0 < 2成立,输出world,,在for循环中case 2:如同标号,被忽略,进而输出bye.,return退出。
当i=1时,满足case 1,输出hello,同时也经过飞线,直接跳进了for循环中,1 < 2成立,++i,i=2,输出world,,case 2:如同标号,被忽略,进而输出bye.,return退出。
当i=2时,满足case 2,输出bye.,return退出。
当i=3时,不满足任何case。
这种反常的特性有一个著名的应用就是达夫设备(Duff’s device),主要用于循环展开以优化性能。
#include <iostream>
// 使用 case 来完成 duff's device
void private_memcpy(char *to, const char *from, size_t count) {
size_t n = (count + 7) / 8;
#define COPY *to = *from;
#define ADVANCE to++, from++;
switch (count % 8) {
case 0: do { COPY ADVANCE
case 7: COPY ADVANCE
case 6: COPY ADVANCE
case 5: COPY ADVANCE
case 4: COPY ADVANCE
case 3: COPY ADVANCE
case 2: COPY ADVANCE
case 1: COPY ADVANCE
} while (--n > 0);
}
#undef COPY
#undef ADVANCE
}
int main() {
const char from[] = "jintianxiaomidaobilema";
char to[sizeof from];
private_memcpy(to, from, sizeof from);
std::cout << to << std::endl;
return 0;
}
Asio的无栈协程也是基于飞线实现的。