tags:

views:

647

answers:

4

if i have a

signed char * p;

and i do a comparison

if( *p == 0xFF ) break;

it will never catch 0XFF, but if i replace to -1 it will...

if( *p == (signed char)0xFF ) break;

will catch ... how come ? is it something with sign flag ? i though that 0xFF == -1 == 255

+25  A: 

The value 0xFF is a signed int value. C will promote the *p to an int when doing the comparison, so the first if statement is equivalent to:

if( -1 == 255 ) break;

which is of course false. By using (signed char)0xFF the statement is equivalent to:

if( -1 == -1 ) break;

which works as you expect. The key point here is that the comparison is done with int types instead of signed char types.

Greg Hewgill
0xFF is signed, not unsigned. 0xFFU is the unsigned version. Only *p needs to be promoted.
Niall
Niall: You're quite right; I'll update the answer.
Greg Hewgill
+2  A: 

It casts to an int for the first comparison since 0xFF is still considered an int, meaning your char is -128 to 127, but the 0xFF is still 255.

In the second case your telling it that 0xFF is really an signed char, not an int

Fire Lancer
+3  A: 

Integer literals have signed int type. Since 0xFF is a signed int, the compiler converts *p to a signed int and then does the comparison.

When *p is -1, which is then converted from a signed char to a signed int, it is still -1 which has a representation of 0xFFFFFFFF, which is not equal to 0xFF.

Niall
+1  A: 

0xff will be seen as an integer constant, with the value of 255. You should always pay attention to these kind of comparison between different types. If you want to be sure that the compiler will generate the right code, you should use the typecast:

if( *p == (signed char)0xFF ) break;

Anyway, beware that the next statement will not work the same way:

if( (int)*p == 0xFF ) break;

Also, maybe it would be a better idea to avoid signed chars, or, it you must use signed chars, to compare them with signed values such as -1 in this case:

if( *p == -1 ) break;

0xff==-1 only if those values would be assigned to some char (or unsigned char) variables:

char a=0xff;
char b=-1;
if(a==b) break;
botismarius