一开始发现这个问题,是在switch中使用了const int类型的量作为case,举例如下:
int main(void)
{
const int c[3] = {
0, 1, 2};
int a = 0;
switch (a)
{
case c[0]:
a = c[1];
break;
case c[1]:
a = c[2];
break;
case c[2]:
a = c[0];
break;
default:
a = c[0];
}
return 0;
}
GCC编译出现了错误: case label does not reduce to an integer constant。
回到switch的用法看看,case后面能够使用什么量呢?
答案是:int型常量、char型常量、enum型常量、sizeof表达式&经过强制类型转换后的浮点型常量。
…it is worth looking briefly at what an integral constant expression is, since that is what must follow the case labels in a switch statement. Loosely speaking, it is any expression that does not involve any value-changing operation (like increment or assignment), function calls or comma operators. The operands in the expression must all be integer constants, character constants, enumeration constants, sizeof expressions and floating-point constants that are the immediate operands of casts. Any cast operators must result in integral types.
——https://publications.gbdirect.co.uk/c_book/chapter3/flow_control.html
也就是说这样写case是可以的:
typedef enum{
ZERO,
ONE
}numbers;
case 0: //integer constant
break;
case 'A': //character constant
break;
case ONE: //enumeration constant
break;
case sizeof(int): //sizeof expressions
break;
case (int)5.0:
break;
那么const在C语言中的作用是?
——准确地说,const in C does not mean something is constant. It just means a variable is read-only,表示只读而非常量,因此是不能用在case之后的。
BTW,C语言中常量除了可以用enum还可以用#define定义。