Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is this comparison always true?

I have the following code in my file:

unsigned char * pData = new unsigned char...

...

if(pData[0] >= 160 && pData[0] <= 255)

When I compile it, I get a warning from the compiler (gcc):

Warning: comparison is always true due to limited range of data type

How can this be? Isn't the range of an unsigned char 0-255? I'm confused.

like image 647
Nathan Osman Avatar asked Oct 01 '10 03:10

Nathan Osman


3 Answers

If the range of unsigned char is from 0 to 255 and pData[0] is a char then pData[0] <= 255 will always be true.

like image 106
James McNellis Avatar answered Nov 12 '22 00:11

James McNellis


The expression pData[0] <= 255 is always true since the range of unsigned char is 0..255 (in your particular implementation).

It's only complaining about that bit of the expressions since pData[0] >= 160 can be true or false.

Keep in mind that the range of an unsigned char need not be 0..255 for all implementations (ISO C standards do not mandate this).

like image 36
paxdiablo Avatar answered Nov 12 '22 00:11

paxdiablo


The second part of the comparison is redundant. It is always less than or equal to 255.

like image 3
wallyk Avatar answered Nov 12 '22 00:11

wallyk