case label does not reduce to an integer constant

一开始发现这个问题,是在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定义。

  • 9
    点赞
  • 25
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值