ARM Technical Support Knowledge Articles

INCORRECT VALUE STORED IN CHAR

Applies to: C51 C Compiler

Answer


Information in this article applies to:


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.

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

Article last edited on: 2001-04-16 00:00:00

Rate this article

[Bad]
|
|
[Good]
Disagree? Move your mouse over the bar and click

Did you find this article helpful? Yes No

How can we improve this article?

Link to this article
Copyright © 2011 ARM Limited. All rights reserved. External (Open), Non-Confidential