C/C++黑魔法-另类switch 发表于 2019-03-23 介绍duff写法与范围判断 duff写法123456789int 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);} 用于循环优化,提高性能。但现代编译器已经支持得很好了。 输出11 2 3 4 0 1 2 3 4 范围判断12345678910111213141516int 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编译器支持 输出14-6: 5