加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 07:20:38 所属栏目:百科 来源:网络整理
导读:如果我使用clang编译以下简单程序(test.c) #include stdio.htypedef enum { a,b} sample_enum_t;int main() { sample_enum_t sample_enum = -1; if (sample_enum == -1) { printf("Equalsn"); }} 编译给了我一个警告: $clang -o test test.ctest.c:11:21:
如果我使用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("Equalsn");
    }
}

编译给了我一个警告:

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读