dimba
dimba

Reputation: 27631

Strange condition evaluation

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

Upvotes: 3

Views: 137

Answers (1)

F&#39;x
F&#39;x

Reputation: 12328

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.

Upvotes: 1

Related Questions