Signed Bitfields

A common mistake is to use signed bitfields, but testing them as if they were unsigned. Signed bitfields have a value of -1 or 0. Consider the following example shown in the following listing).

Listing: Testing a signed bitfield as being unsigned
typedef struct _B {   signed int b0: 1;} B; 
  B b; 
if (b.b0 == 1) ... 

The Compiler issues a warning and replaces the 1 with -1 because the condition (b.b0 == 1) is always false. The test (b.b0 == -1) is performed as expected. This substitution is not ANSI compatible and will not be performed when the -Ansi: Strict ANSI compiler option is active.

The correct way to specify this is with an unsigned bitfield. Unsigned bitfields have the values 0 or 1.

Listing: Using unsigned bitfields
typedef struct _B {   unsigned b0: 1; 
} B; 
  B b; 
  if (b.b0 == 1) ... 

Because b0 is an unsigned bitfield having the values 0 or 1, the test (b.b0 == 1) is correct.