Reputation: 73235
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.
Upvotes: 9
Views: 5090
Reputation: 25527
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.
Upvotes: 0
Reputation: 6233
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)
Upvotes: 0
Reputation: 57784
The second part of the comparison is redundant. It is always less than or equal to 255.
Upvotes: 3
Reputation: 882028
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).
Upvotes: 5
Reputation: 355167
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
.
Upvotes: 11