9

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.

Nathan Osman
  • 71,149
  • 71
  • 256
  • 361

5 Answers5

11

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
  • 348,265
  • 75
  • 913
  • 977
5

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
  • 854,327
  • 234
  • 1,573
  • 1,953
3

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

wallyk
  • 56,922
  • 16
  • 83
  • 148
0

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
  • 6,134
  • 4
  • 33
  • 55
0

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
  • 24,777
  • 4
  • 73
  • 129