C语言陷阱之Enum

问题

先看代码:

typedef enum {
	xxx_inv = -1,
	xxx_0   = 0,
	xxx_1   = 1,
	xxx_max = 64,
} enum_t;

enum_t idx;
for (idx = 0; idx < 256; idx++) {
	// do something with idx
	func(idx);
}

上面的代码有问题吗?如果你觉得没有,并把这样的代码写到了实际的工程代码中,那么恭喜你为后人埋了一个超级大的坑,这个坑会像幽灵一样随着你的编译器变化而变化,时有时无,若隐若现^_^

详解

先来看c99标准中对enum的定义:

6.7.2.2 Enumeration specifiers
[...]
Constraints
The expression that defines the value of an enumeration constant shall be an integer constant expression that has a value representable as an int.
[...]
Each enumerated type shall be compatible with char, a signed integer type, or an unsigned integer type. The choice of type is implementation-defined, but shall be capable of representing the values of all the members of the enumeration.

大概解释一下,对于enum中定义的常量xxx_0, xxx_1等,它们是int, 但对于enum_t这个类型,它的实际类型是同编译器实现相关的,只要定义来能够表示enum_t中的所有数就可以了。
这也就是说,对于有的编译器,enum_t实际type是char,因为其数值范围从-1~64, char完全够了,但也有编译器把它解释成int。这样一来,我们上面的代码在实际使用不同的编译器器会出现完全不一样的结果。

如果enum_tchar, 我们再来看下上面的代码:

char idx;
for (idx = 0; idx < 256; idx++) {
	// do something with idx
	func(idx);
}

What! 由于char的数值范围是-128到127,idx永远也加不到256, 死循环了。。。
更恐怖是的,如果有的函数还定义了这样的idx,用来作为数组的下标,比如我们上面的func函数,那数组访问有可能在不知不觉中就越界了。

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值