hy*******@gmail.com wrote:
...
temp[0] = 0xFF;
temp[1] = 0xEE;
if(temp[0] == 0xFF) // returns false but if(temp[0] == (char)0xFF) //
returns true
...
Let's get rid of the variables and convert everything to decimals. The
above comparison is equivalent to
if ((char) 255 == 255)
Before the comparison takes place, the language will apply arithmetic
promotions to both operands and promote them to type 'int' (assuming
that in your compiler the range of 'char' fits into the range of 'int').
The actual comparison will be carried out for 'int' operands. This means
that what you wrote above is equivalent to
if ((int)(char) 255 == (int) 255)
Now, let's assume that in your compiler the type 'char' is signed and
it's range is too small to accommodate the value 255. In that case the
result of '(char) 255 ' conversion is implementation-defined. Most
likely it is going to be some negative value, say, '-1'. Under that
assumption, the above comparison is equivalent to
if (-1 == 255)
and, obviously, the result of this comparison is 'false'.
Once you add the extra 'char' cast on the right-hand side, you end up with
if ((int)(char) 255 == (int)(char) 255)
which is going to be equivalent to
if (-1 == -1)
for the very same reasons (under the very same assumptions). This is, of
course, 'true'.
--
Best regards,
Andrey Tarasevich