Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C variable and constant value comparison not matching

Tags:

c

If I have:

signed char * p;

and I do a comparison:

if ( *p == 0xFF )
   break;

it will never catch 0XFF, but if I replace it with -1 it will:

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

How can this happen? Is it something with the sign flag? I though that 0xFF == -1 == 255.

like image 846
CiNN Avatar asked Sep 14 '08 09:09

CiNN


1 Answers

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.

like image 199
Greg Hewgill Avatar answered Oct 27 '22 04:10

Greg Hewgill