Signed Bitfields

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

Listing: Testing a Signed Bitfield as 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) does not make sense, that is, it is always false. The test (b.b0 == -1) performs as expected. This substitution is not ANSI compatible and will not be performed when the -Ansi: Strict ANSI compiler option is active.

Use an unsigned bitfield to test.Unsigned bitfields have the values 0 or 1, as shown in the following listing.

Listing: Using Unsigned Bitfields
typedef struct _B {
  unsigned b0: 1;

} B;

  B b;

  if (b.b0 == 1) ...

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

Note: To save memory, it is recommended implementing globally accessible boolean flags as unsigned bitfields of width 1. However, it is not recommended using bitfields for other purposes because using bitfields to describe a bit pattern in memory is not portable between compilers, even on the same target, as different compilers may allocate bitfields differently.

For information about bitfield allocation by the Compiler, see the Data Types section in HC(S)08 Backend .