微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐