Question

This is a question relating the c99 standard and concerns integer promotions and bitwise negations of unsigned char.

In section 6.5.3.3 it states that:

The integer promotions are performed on the operand, and the result has the promoted type. If the promoted type is an unsigned type, the expression ~E is equivalent to the maximum value representable in that type minus E.

Am I understanding that correctly when I say that, that means that:

unsigned int ui = ~ (unsigned char) ~0; // ui is now 0xFF00.

My confusion stems from a discussion with a collegue where he is seeing the following behaviour in our compiler.

unsigned char uc = 0;
unsigned char ucInverted = ~0;

if( ~uc == ~0 )              // True, obviously
if( ~ucInverted == ~(~0) )   // False as it evaluates to: 0xFF00 == 0x0000
if( ~uc == ucInverted )      // False as it evaluates to: 0xFFFF == 0x00FF
if( uc == ~ucInverted )      // False as it evaluates to: 0x0000 == 0xFF00

This behaviour is confirmed with gcc.

Is it possible to get proper expected char comparisons where each of these cases will evaluate to true?

Was it helpful?

Solution

~uc is of type int (value 0xFFFF). ucInverted is of type unsigned char (value 0xFF), which is then promoted to int (value 0x00FF). Thus they are not equal.

I guess you could do if ((unsigned char)~uc == ucInverted). Both operands will still undergo promotion, but they will have identical values before the promotion.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top