Integer promotions: why uint8_t arithmetic surprises you
Byte-sized register mirrors and packet fields make it tempting to assume every expression involving a byte is evaluated at eight bits. In C that is not the rule. A narrow type whose values fit in int promotes to int before many arithmetic and bitwise operations. A condition can therefore compare a value quite different from the value ultimately stored in the byte.
The contract
An eight-bit unsigned object converted from 256 becomes zero because unsigned conversion is modulo one more than the maximum representable value. This does not mean signed overflow is defined or that the intermediate expression was eight bits wide. Make the desired conversion explicit at the point where your format requires it.
A small executable example
#include <stdint.h>
#include <assert.h>
#include <stdio.h>
int main(void) {
uint8_t a = 255;
assert(a + 1 == 256);
uint8_t wrapped = (uint8_t)(a + 1);
assert(wrapped == 0);
printf("sum=%d byte=%u\n", a + 1, (unsigned)wrapped);
}
sum=256 byte=0
Compiled with -Wall -Wextra -Werror and run under AddressSanitizer + UBSan.
Learning this for work or an interview? Lessons 1 and 2 of DSA for Firmware are free, with labs and C exercises. Start Lesson 1
What the example does not establish
The host program assumes uint8_t exists; its maximum is exactly 255. It demonstrates that the promoted sum fits in int, which has a minimum range sufficient for 256. For wider operands, analyze the common type and bounds before multiplication or shifting. Casting after an overflowing signed operation does not repair that operation. Unsigned bitwise complement also needs attention because a narrow operand can be promoted before the complement.
Checks to add in your own project
Test zero, the highest byte value, and values around any protocol field boundary. Compile with conversion warnings where available and examine each narrowing conversion for intent. A reviewed conversion should communicate whether you are encoding a modulo counter, enforcing saturation, or rejecting an out-of-range input. These are three different requirements.
DSA for Firmware teaches it one real bug at a time.
- 28 lessons, each starting from a real firmware bug.
- 110 C exercises with tests, and a reference solution for every one.
- Lessons 1 and 2 are free. No sign-up.
Get the next article by email
One short email when a new article or free lesson is published. No spam. Unsubscribe at any time by replying to any email. See the privacy policy.