INF: Unsigned Characters and Arithmetic Operators

ID Number: Q45237

5.10 6.00 6.00a 6.00ax 7.00 | 5.10 6.00 6.00a

MS-DOS | OS/2

Summary:

In the sample program below, two unsigned character variables are

compared. The conditional always evaluates to true, even when x and y

are complements. When the assembly code produced is examined, it

appears as though the compiler is generating code to compare two

unsigned integers, not unsigned characters.

Sample Code

-----------

/* Compile options needed:

*/

#include <stdio.h>

void main (void)

{

unsigned char x, y;

x = 0;

y = 255;

if (x != (~y))

printf ("y is not a complement of x\n");

else

printf ("y is a complement of x\n");

}

More Information:

The code generated in this case is correct. Operands of unsigned

character type are promoted to unsigned integer type when using

arithmetic operators.

For this sample code to work as you intended, cast the "~y" as

unsigned character, as follows:

if (x != (unsigned char)(~y))

printf ("y is not a complement of x\n");

else

printf ("y is a complement of x\n");

Additional reference words: 5.00 5.10 6.00 6.00a 6.00ax 7.00