Keil Logo

GENERAL: LOGICAL NOT ('~') GIVES INCORRECT RESULTS


Information in this article applies to:

  • C166 All Versions
  • C251 All Versions
  • C51 All Versions

QUESTION

I get strange results when I compare character values. This is shown in the following example:

unsigned char a = 0x7F;

if (a == ~0x80)  {  // ~0x80 should match 0x7F
  a = 0;            // and therefore a should be set to zero
}

The comparison fails. Why? Isn't ~0x80 identical to 0x7F?

ANSWER

ANSI C requires that expression values are promoted to integer data types unless otherwise specified.

Therefore, the value of the expression ~0x80 is 0xFF7F (since an int is 16-bits). To get the results you expect, you must explicitly cast the value as follows:

unsigned char a = 0x7F;

if (a == ((unsigned char) ~0x80))  {  // gives 0x7F
  a = 0;                              // and the test is OK.
}

MORE INFORMATION

Refer to the ANSI C Standard (ANSI/ISO 9899-1990), section 6.2.1.5 - Usual Arithmetic Conversions.

SEE ALSO

Last Reviewed: Wednesday, December 4, 2002


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.