ABC of Electronics cosycom.com
EMBEDDED SYSTEMS & MICROCONTROLLERS · PAGE 85

C Pitfalls: Undefined Behaviour and Overflow

Bugs the compiler will not warn about.

Signed integer overflow, reading an uninitialised variable, and using memory after it has gone out of scope are all undefined, so anything may happen. Unsigned arithmetic wraps predictably.

Beware of integer promotion: small types are widened before maths. Mix signed and unsigned carefully, compare like with like, and turn on all compiler warnings.

EXAMPLE
uint8_t a = 200, b = 100;
uint16_t sum = a + b;      /* 300: promoted, so no wrap here */
uint8_t  wrapped = a + b;  /* 44: wrapped when stored */