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.
}
else
{
// 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: , , ,

Leave a Reply