#include <stdio.h> typedef enum { a,b } sample_enum_t; int main() { sample_enum_t sample_enum = -1; if (sample_enum == -1) { printf("Equals\n"); } }
编译给了我一个警告:
$clang -o test test.c test.c:11:21: warning: comparison of constant -1 with expression of type 'sample_enum_t' is always false [-Wtautological-constant-out-of-range-compare] if (sample_enum == -1) { ~~~~~~~~~~~ ^ ~~ 1 warning generated.
如果我执行它以“Equals”打印的程序,那么比较总是假的,这显然是不正确的:
$./test Equals
这是一个铿锵的错误还是我错过了什么?我明白将-1分配给sample_enum变量并不是一个好主意,但它是一个有效的行,并且clang因为该行而没有给我一个警告.
我正在使用clang 3.5.2
解决方法
6.7.2.2 Enumeration specifiers:
Each enumerated type shall be compatible with char,a signed integer type,or an unsigned integer type. The choice of type is implementation-defined,128) but shall be capable of representing the values of all the members of the enumeration. The enumerated type is incomplete until immediately after the } that terminates the list of enumerator declarations,and complete thereafter.
128) An implementation may delay the choice of which integer type until all enumeration constants have been seen.
您依赖于实现定义的行为;您的实现选择的类型是否表示-1是否未由标准定义.
Clang和GCC都使用unsigned int(在我使用gcc 7.0.1和clang 3.8.0测试你的代码时).所以,你的代码是有效的,因为没有代表-1的问题.
所以,这不是一个真正的问题,Clang的诊断有点用处,因为如果你无意中使用了一些你定义的枚举常量范围之外的值.