C/C++黑魔法-另类switch

介绍duff写法与范围判断

duff写法

1
2
3
4
5
6
7
8
9
int n = 1;
switch (n) {
case 0: do { printf("%d ", 0);
case 1: printf("%d ", 1);
case 2: printf("%d ", 2);
case 3: printf("%d ", 3);
case 4: printf("%d ", 4);
} while (n-- > 0);
}
  • 用于循环优化,提高性能。但现代编译器已经支持得很好了。
  • 输出
    1
    1 2 3 4 0 1 2 3 4

范围判断

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int i = 5;
switch (i) {
case 0 ... 3:
std::cout<<"0-3: "<<i<<std::endl;
break;
case 4 ... 6:
std::cout<<"4-6: "<<i<<std::endl;
break;
case 7 ... 9:
std::cout<<"7-9: "<<i<<std::endl;
break;
case 10:
std::cout<<"10"<<i<<std::endl;
default:
break;
}
  • 注意: gnu编译器,mingw编译器支持
  • 输出
    1
    4-6: 5