views:

183

answers:

5

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.

+9  A: 

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.

James McNellis
What a silly mistake! I feel a little embarrassed because this is for a compiler I'm writing :) Even veterans miss things sometimes!
George Edison
+4  A: 

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).

paxdiablo
+3  A: 

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

wallyk
*[facepalm]* Why didn't I see that?
George Edison
Assuming `CHAR_BIT` is 8 and `char` is unsigned.
GMan
@GMan: Yup. It's unsigned.
George Edison
A: 

You should always parenthasise your expressions to avoid ambiguity, such as:

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

Does this solve the problem?

The second comparison is redundant, so use:

if (pData[0] >= 160)
Alexander Rafferty
Operator precedence has nothing to do with this... the relational operators have higher precedence than the binary logical operators.
James McNellis
No, there is no ambiguity. Operator precedence does what I expect it to.
George Edison
A: 

Isn't the range of an unsigned char 0-255?

The range of unsigned char is implementation defined (in contrast to some of the other posts). This is because the number of bits used to represent a char is not 8 always. It is just that a char takes 1 8bit location on your particular implementation and hence 255 is the upper limit.

So in case there is a some other meaning attached to 255 (other than 'numeric_limits<char>::max()'), I think you should still go ahead and use the check, else the check is redundant.

Chubsdad