What is integer promotion?
Short answer: Before most arithmetic, any integer type smaller than int (char, short, uint8_t, uint16_t, bit-fields) is converted to int (or to unsigned int if int cannot hold all its values). The operation is done in int, and the result is only narrowed again if you store it into a smaller type. This leads to surprising results with ~, shifts and comparisons.
uint8_t a = 0xFF;
if (~a == 0x00) { } /* never true: ~a is int ~255 = 0xFFFFFF00 (-256) */
if ((uint8_t)~a == 0x00) { } /* true */
uint8_t x = 200, y = 100;
uint8_t z = x + y; /* computed as int 300, stored as 300 % 256 = 44 */
int w = x + y; /* 300: no overflow, because the math was done in int */
uint16_t u = 0xFFFF;
uint32_t r = u * u; /* u promoted to *signed* int on 32-bit targets:
65535 * 65535 overflows int -> undefined behaviour! */
uint32_t ok = (uint32_t)u * u;
Usual arithmetic conversions (what happens after promotion when the two operands differ): the operand with the "lower" type is converted to the other's type; if one is unsigned and has the same or greater rank, the signed one becomes unsigned.
Where it bites in embedded code
- Inverting a byte mask:
reg8 &= ~MASK8;is fine (the result is truncated back), but comparisons with~byteare not. - Shifts:
uint8_t b = 0x80; uint32_t v = b << 24;promotesbto signedint, and0x80 << 24overflows into the sign bit: undefined behaviour. Write(uint32_t)b << 24. - Checksums accumulated in a
uint8_tbehave correctly only because the result is truncated on every assignment. - On 16-bit MCUs (
int= 16 bits),uint16_tpromotes tounsigned int, so the same code behaves differently than on a 32-bit Arm.
MISRA C has the "essential type" rules exactly to catch these issues; compiler warnings such as -Wconversion and -Wsign-conversion help too.