【发布时间】:2021-09-27 22:36:14
【问题描述】:
我正在尝试了解我的 gcc 设置中的以下行为:
% cat t.c
#include <limits.h>
// -Wtype-limits
int type_limits1(unsigned long ul) {
return ul >= 0;
}
int type_limits2(unsigned long ul) {
return ul <= ULONG_MAX;
}
导致:
% gcc -c -std=gnu99 -Wtype-limits -x c t.c
t.c: In function ‘type_limits1’:
t.c:5:13: warning: comparison of unsigned expression >= 0 is always true [-Wtype-limits]
return ul >= 0;
^~
为什么类型限制警告限制为 0 常量值,并且不处理 ULONG_MAX ?这是因为0 是语言的一部分,而#define ULONG_MAX 不是(我猜有一个很好的理由不实施,我只是看不到哪一个)。
我可以使用 clang 重现相同的行为:
% clang -c -std=gnu99 -Weverything -Wno-missing-prototypes -x c t.c
t.c:5:13: warning: result of comparison of unsigned expression >= 0 is always true [-Wtautological-unsigned-zero-compare]
return ul >= 0;
~~ ^ ~
1 warning generated.
使用:
% gcc --version
gcc (Debian 8.3.0-6) 8.3.0
和
% clang --version
clang version 7.0.1-8+deb10u2 (tags/RELEASE_701/final)
【问题讨论】:
-
给定
unslgned long ul,ul怎么可能小于零或大于ULONG_MAX? -
问题是:
Why is the type-limits warning limited to the 0 constant value[...] -
警告通常是可选的——它们是编译器编写者花更多时间告诉你的,“嘿,我们认为这很狡猾。你可能需要重新考虑你的代码。”如果 C 标准中没有要求发出诊断,则不应期望生成诊断。
-
Why is the type-limits warning limited to the 0 constant value, and does not handle ULONG_MAX ?没有具体原因,有人这样写编译器。 -
@MicroVirus 为什么不将其发布为答案?