gcc 和有符号/无符号比较的奇怪警告行为
我有以下代码:
unsigned int a;
if (a > numeric_limits<int>::max())
do_stuff();
编译时,gcc 抱怨
警告:“有符号和无符号之间的比较”
好吧,我明白
但是,使用以下代码:
unsigned int a;
if (a > (numeric_limits<int>::max()))
do_stuff();
警告不再显示,我真的不知道为什么...... 这种行为有任何逻辑原因还是我做错了什么?!
I have the following code :
unsigned int a;
if (a > numeric_limits<int>::max())
do_stuff();
When compiling, gcc complains about
warning: "comparison between signed and unsigned"
OK, I understand
But, with the following code :
unsigned int a;
if (a > (numeric_limits<int>::max()))
do_stuff();
The warning is no longer displayed and I really don't know why...
Is there any logical reason for such a behavior or am I doing something wrong?!
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这是因为它是一个错误。请参阅错误 50012
It's because it is a bug. See bug 50012
我目前无法访问 C++ 编译器来测试这一点,但我认为这可能会在没有任何警告的情况下工作:
I do not currently have access to a C++ compiler to test this, but I think this might work without any warnings:
答案在于 gcc 处理 int 和 unsigned int 的方式。
unsigned int
和int
都存储一个 2 字节值。它们之间的区别在于unsigned int
不支持负值。它只能存储 0-65,535 之间的值。当 GCC 看到 int 和 unsigned int 之间的比较时,它会将 int 转换为正数。例如,如果
int
的值为-2,它会将其转换为2。但是如果int 前面有() 运算符。 (整数)。 GCC 将其解释为正数(但仍将其转换)并且不发出警告。The answer lies in the way gcc handles
int
andunsigned int
.unsigned int
andint
both store a 2 byte value. The difference between them is thatunsigned int
does not support negative values. It can only store values from 0-65,535.When GCC sees a comparison between int and unsigned int it converts the int to a positive number. e.g if the value of the
int
is -2 it will convert it to 2. But if the int is preceded by the () operator . (int). GCC interprets it as a positive number (but still converts it) and doesn't give a warning.