异常状况评估
以下代码:
#include <stdint.h>
int main() {
uint8_t Byte;
if (Byte < 0) { }
}
发出以下编译警告:
main.cpp: In function `int main()':
main.cpp:6: warning: comparison is always false due to limited range of data type
这很好。但是,当我将条件更改为:时,
(1) if (true || (Byte < 0)) { }
我仍然收到警告,而我希望收到类似“比较始终为真...”的警告:)
如果我将字节声明更改为:
(2) uint32_t Byte;
警告就会消失。
我该如何解释这种行为?
我的系统是 RHEL 5.3 64 位,附带 gcc 4.1.2。
编辑:
(1) 不是问题,我只是误解了编译器警告。 它并没有说整个 if 是假,而是说“Byte < 0”。
所以问题只是(2)——为什么Byte类型会触发编译器警告。 常量“0”是 int 类型,因此它有 4 个字节。所以它一定与 uint8_t 与 int 的比较有关
The following code:
#include <stdint.h>
int main() {
uint8_t Byte;
if (Byte < 0) { }
}
emits the following compilation warning:
main.cpp: In function `int main()':
main.cpp:6: warning: comparison is always false due to limited range of data type
This is fine. But when I change condition to:
(1) if (true || (Byte < 0)) { }
I still receive the warning, while I expect to receive warning like "comparison is always true ..." :)
If I change Byte declaration to:
(2) uint32_t Byte;
warning disappears.
How can I explain the behavior?
My system is RHEL 5.3 64 bit shipped with gcc 4.1.2.
EDIT:
(1) is not a problem, I just misunderstood compiler warning.
It doesn't says that the whole if is false but rather "Byte < 0".
So the problem is only (2) - why Byte type triggers compiler warning.
Constant "0" is of type int, so its 4 bytes. So its must be related to comparison if uint8_t with int
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
将无符号值与 0 有符号 int 进行比较时,该值首先(隐式)转换为 int。由于 uint8_t 介于 0 到 255 之间,因此转换为 32 位 int 时它为正。
另一方面,uint32_t 介于 0 和 2^32-1 之间,因此当转换为 32 位 int 时,它可能会换行并变为负值(所有大于或等于 2^31 的值都将转换为负 int事实上)。因此,您的比较并不总是正确的,编译器是正确的。
When comparing an unsigned value to your 0 signed int, the value is first (implicitly) cast into an int. As an uint8_t is between 0 and 255, it is positive when cast into a 32-bit int.
On the other hand, you uint32_t is between 0 and 2^32-1, so when cast into a 32-bit int, it may wrap and become negative (all values higher than or equal to 2^31 will be cast into negative int values, in fact). So, your comparison isn't always true, and the compiler is right.