clang tutological-constant-out-of-range-compare warning

如果我使用clang编译以下简单程序(test.c)

#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

解决方法

暂时忽略Clang是对还是错,让我们看一下标准所说的内容.

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的诊断有点用处,因为如果你无意中使用了一些你定义的枚举常量范围之外的值.

相关文章

本程序的编译和运行环境如下(如果有运行方面的问题欢迎在评...
水了一学期的院选修,万万没想到期末考试还有比较硬核的编程...
补充一下,先前文章末尾给出的下载链接的完整代码含有部分C&...
思路如标题所说采用模N取余法,难点是这个除法过程如何实现。...
本篇博客有更新!!!更新后效果图如下: 文章末尾的完整代码...
刚开始学习模块化程序设计时,估计大家都被形参和实参搞迷糊...