一、一直以为case后面只能接整型常量或常量表达式。也确实在标准C中确实不能接范围表达式。
但是在开发中却碰见了case 1 … 3 (省略号两侧有空格)这种接范围的用法。gcc/g++中case语句后面可以接一个范围。
二、官方的解释Using and Porting the GNU Compiler Collection (GCC): C Extensions
4.21 Case RangesYou can specify a range of consecutive values in a single case label, like this: case low ... high:This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive.This feature is especially useful for ranges of ASCII character codes: case 'A' ... 'Z':Be careful: Write spaces around the ..., for otherwise it may be parsed wrong when you use it with integer values. For example, write this: case 1 ... 5:rather than this: case 1...5:
三、测试实例
#include int main(){int value = 0;switch (value){case 1 ... 3:printf("dac value = %d ...\n",value);break;case 4 ... 6:printf("adc value = %d...\n",value);break;default:printf("failed value = %d...\n",value);break;}value = 5 ;switch (value){case 1 ... 3:printf("dac value = %d ...\n",value);break;case 4 ... 6:printf("adc value = %d...\n",value);break;default:printf("failed value = %d...\n",value);break;}return(0);}
标准输出:failed value = 0...adc value = 5...
四、linux kernel 中也是可以这么用,编译通过。
五、参考文章
C语言switch case语句的case后面不能接范围?_case可以接一个范围吗_铁头小哥的博客-CSDN博客
C语言switch-case语句的范围表示_c语言switchcase怎么定范围_刺客世家的博客-CSDN博客