embedded software boot camp

Coding Standard Rule #8: Don’t Mix Signed and Unsigned Data

Thursday, April 2nd, 2009 by Michael Barr

Rule: Signed integers shall not be combined with unsigned integers in comparisons or expressions. In support of this, decimal constants meant to be unsigned should be declared with a ‘u’ at the end.

Example (don’t):

uint8_t a = 6u;
int8_t b = -9;

if (a + b < 4)
// This correct path should be executed
// if -9 + 6 were -3 < 4, as anticipated.
// This incorrect path is actually executed
// because -9 + 6 becomes (0xFF – 9) + 6 = 252.

Reasoning: Several details of the manipulation of binary data within signed integer containers are implementation-defined behaviors of the C standard. Additionally, the results of mixing signed and unsigned data can lead to data-dependent bugs.

Coding Standard Rule #7
Coding Standard Rule #9

These rules are excerpts of the Embedded C Coding Standard book.

Tags: , , ,

One Response to “Coding Standard Rule #8: Don’t Mix Signed and Unsigned Data”

  1. Simon Lawrence says:

    While I totally agree with this rule, I believe the example could use some clarification. Surely the example is only true for a compiler where sizeof(int) == 1. It’s been a long time since I’ve used an 8051, however from memory; int was 16 bit even though the processor is 8 bit. I know that’s just one example but given the popularity of low cost 32 bit processors today maybe the example should be updated or explicitly state the int size.
    As a side note -9 is 1111 0111 which is 247, and therefore -9 + 6 should be 253.

Leave a Reply