C规范(6.7.2.2)的枚举特定部分规定:
The identifiers in an enumerator list are declared as constants that have type int and
may appear wherever such are permitted.127) An enumerator with = defines its
enumeration constant as the value of the constant expression. If the first enumerator has
no =,the value of its enumeration constant is 0.
所以我应该能够使用与int常量相同的枚举成员.在这个小样本程序中:
enum first { a,b }; enum second { c,d }; int main(){ enum first myf = a; enum second mys = c; if(myf == mys) printf("same value\n"); return 0; }
当编译gcc -Wall -Werror时,我收到消息:
error: comparison between ‘enum first’ and ‘enum second’ [-Werror=enum-compare]
我知道,如果我将myf和MysqL的类型转换为int,那么编译器将会很开心,就像我可以用myf和mys的值来设置几个int,并进行比较;但为什么我要做这些任何一个来摆脱警告呢?为什么首先存在这个警告?这样做,我看不到会有一些危险.
注意:我已经阅读了关于这个枚举比较标志的gcc文档,但它并没有说什么:
-Wenum-compare
Warn about a comparison between values of different enumerated types. In C++ enumeral mismatches in conditional expressions are also diagnosed and the warning is enabled by default. In C this warning is enabled by -Wall.
解决方法
enum Day { Sunday,Monday,Tuesday,Wednesday,Thursday,Friday,Saturday }; enum Month { January,February,March,April,May,June,July,August,September,October,November,December }; enum Day day = Wednesday; enum Month month = April; if (day == month) { ... }
这个评估是真实的,但总体上来说,这种比较并没有多大意义.如果你知道你的意思,那么typecast会说服编译器,正如你所说.