Keil Logo

C51: Compare 'char' Variable with Const Value is Never True


Information in this article applies to:

  • C166
  • C251
  • C51

SYMPTOMS

I have declared a char and assigned it a value of C5H as follows:

char foo = 0xC5;

However, when I compare the variable to C5H in an if statement it does not match. If I compare the variable to FFC5H it does match.

if (foo == 0xC5)
{
  /* does not reach here */
}
if (foo == 0xFFC5)
{
  /* does reach here */
}

What is going on?

CAUSE

The variable foo is signed. This means that the most significant bit is the sign bit and indicates whether the value is negative or positive. The value C5H has the sign bit set indicating a negative value (-59).

When the 'if' statement is executed the variable is always promoted to an int. The upper byte is a copy of the sign bit. E.g. for positive numbers it is 00H and for negative numbers it is FFH. In order for a negative number to match it must start with 'FF' as in the example above. For the comparison, a value of C5H is not in the range of the char and will therefore never be matched.

Turning off integer promotion will not affect this operation.

RESOLUTION

If you wish to use hexadecimal values in the range 00H to FFH then declare the variable as an unsigned char.

If you wish to use decimal values in the range -127 to 128 then declare the variable as a char and assign it decimal values, rather than hexadecimal values where confusion can occur.

SEE ALSO


Last Reviewed: Thursday, February 25, 2021


Did this article provide the answer you needed?
 
Yes
No
Not Sure
 
  Arm logo
Important information

This site uses cookies to store information on your computer. By continuing to use our site, you consent to our cookies.

Change Settings

Privacy Policy Update

Arm’s Privacy Policy has been updated. By continuing to use our site, you consent to Arm’s Privacy Policy. Please review our Privacy Policy to learn more about our collection, use and transfers
of your data.