开发者

Strange condition evaluation

开发者 https://www.devze.com 2023-01-24 13:19 出处:网络
The following code: #include <stdint.h> int main() { uint8_t Byte; if (Byte < 0) { } } emits the following compilation warning:

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


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号