问题
先看代码:
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_t
是char
, 我们再来看下上面的代码:
char idx;
for (idx = 0; idx < 256; idx++) {
// do something with idx
func(idx);
}
What! 由于char的数值范围是-128到127,idx
永远也加不到256, 死循环了。。。
更恐怖是的,如果有的函数还定义了这样的idx,用来作为数组的下标,比如我们上面的func
函数,那数组访问有可能在不知不觉中就越界了。