Skip to content
Tactiverge

C types, sizes and integer overflow

Why embedded C uses fixed-width types like uint8_t and int32_t, what happens when a value no longer fits, and how to write arithmetic that stays correct.

Lesson 2 of 6 · 30 min · Self-paced · Free

When numbers run out of room

A robot's wheel encoder counts pulses into a variable. After a long drive, the count suddenly jumps from a large positive number to a large negative one, and the robot believes it has teleported backwards. Nothing is broken: the variable simply ran out of bits. In embedded systems, where memory is precious and variables are often small, knowing exactly how big each number is, and what happens at its limits, is basic engineering hygiene.

The problem with int

In C, the size of int is not fixed by the language. The standard only promises it is at least 16 bits. On a typical laptop it is 32 bits; on many 8-bit microcontrollers it is 16 bits. Code that works on your laptop can therefore overflow on the chip.

The solution is the <stdint.h> header, part of C99, which provides fixed-width types whose size never changes:

type        bits   range
int8_t      8      −128 to 127
uint8_t     8      0 to 255
int16_t     16     −32 768 to 32 767
uint16_t    16     0 to 65 535
int32_t     32     −2 147 483 648 to 2 147 483 647
uint32_t    32     0 to 4 294 967 295

The u means unsigned: no negative numbers, so the whole range is available for positive values. An N-bit unsigned type holds 0 to 2^N − 1. A signed type uses two's complement and holds −2^(N−1) to 2^(N−1) − 1.

Choose types deliberately. A raw ADC reading of 0 to 1,023 fits in uint16_t. A count of milliseconds since power-on needs uint32_t. A temperature that might go below zero needs a signed type. Smaller types save RAM, which matters when you have only 2 KB.

Unsigned overflow wraps around

When an unsigned value goes past its maximum, C defines exactly what happens: it wraps around to zero, like a car's mileage counter rolling over. Mathematically, the result is taken modulo 2^N. So for uint8_t, 255 + 1 = 0 and 250 + 10 = 260 − 256 = 4.

Signed overflow is undefined

For signed types, overflow is undefined behaviour. The C standard places no requirement on what happens. In practice you often see wrap-around to a large negative number, as in the encoder story, but optimising compilers are allowed to assume overflow never happens and may generate code that behaves in surprising ways. The rule: never let signed arithmetic overflow. If you need wrap-around, use unsigned types, where it is guaranteed.

Seeing it happen

This portable program runs on any computer. Compile it with cc -std=c99 -Wall types.c -o types.

#include <stdio.h>
#include <stdint.h>

int main(void) {
    uint8_t count = 250;
    for (int i = 0; i < 10; i++) {
        count++;                       /* 250 + 10 = 260, but 8 bits hold 0..255 */
    }
    printf("count = %u\n", (unsigned)count);

    uint16_t counts = 1023, vref_mv = 3300;
    uint16_t wrong = counts * vref_mv;            /* result squeezed into 16 bits */
    uint32_t right = (uint32_t)counts * vref_mv;  /* widen first, then multiply */
    printf("wrong = %u, right = %lu\n", (unsigned)wrong, (unsigned long)right);

    int a = -1;
    unsigned int b = 1;
    printf("-1 < 1u is %s\n", (a < b) ? "true" : "false");

    printf("sizes in bytes: %zu %zu %zu\n",
           sizeof(uint8_t), sizeof(uint16_t), sizeof(uint32_t));
    return 0;
}

Output:

count = 4
wrong = 33564, right = 3375900
-1 < 1u is false
sizes in bytes: 1 2 4

Each line teaches something.

Line 1. 250 + 10 = 260, which wraps to 260 − 256 = 4.

Line 2. The true product 1,023 × 3,300 = 3,375,900 needs more than 16 bits. Stored in a uint16_t, it becomes 3,375,900 mod 65,536 = 33,564. That is a plausible-looking number, which makes the bug dangerous. Casting one operand to uint32_t before multiplying makes the whole calculation 32-bit. This is exactly why the ADC lesson's conversion function widened first.

Line 3. When you compare a signed and an unsigned value, C converts the signed one to unsigned. −1 becomes 4,294,967,295 (on a system with 32-bit int), which is not less than 1. Many compilers do not warn about this with -Wall alone; -Wextra adds the warning. Avoid mixing signed and unsigned in comparisons.

Line 4. sizeof reports sizes in bytes, confirming that fixed-width types are the same everywhere.

Integer promotion: a hidden step

In C, arithmetic on types smaller than int first promotes them to int (or unsigned int). That is why uint8_t variables can be added without overflow in the middle of an expression, and only wrap when the result is stored back into a uint8_t. It also explains why the "wrong" product above is computed at full size and then cut down when stored. The rules are subtle; the practical advice is to make the type of every intermediate result explicit when it might be large.

Integer division truncates

7 / 2 in C is 3, not 3.5: integer division throws away the remainder. Combined with overflow, this gives the golden rule for scaled arithmetic: multiply before dividing, in a type wide enough for the product. Compute counts * 3300 / 1024 in 32 bits, not counts / 1024 * 3300, which is 0 for every reading below 1,024.

A real-world warning

On its first flight in 1996, the Ariane 5 rocket was lost about 40 seconds after launch. A key cause was a software conversion of a 64-bit floating-point number into a 16-bit signed integer: the value was too big to fit, the conversion failed, and the guidance system shut down. The code had been reused from Ariane 4, whose slower flight never produced such large values. The lesson for every embedded engineer: know the range of every variable, and check that it still holds when the system changes.

Recap

int has no fixed size, so embedded C uses <stdint.h> types such as uint8_t and int32_t. An N-bit unsigned type holds 0 to 2^N − 1 and wraps around predictably; signed overflow is undefined and must be avoided. Widen before multiplying, multiply before dividing, avoid mixing signed and unsigned in comparisons, and know the range each variable must hold.

Project

Find the limits

Write a short C99 program, compiled with cc -std=c99 -Wall -Wextra, that:

  1. Stores 65,535 in a uint16_t, adds 1, and prints the result. Predict the answer first.
  2. Counts milliseconds in a uint16_t. Calculate by hand how many seconds pass before it wraps, and how many days a uint32_t millisecond counter lasts.
  3. Computes a 12-bit ADC reading of 4,095 times a reference of 3,300 mV, first entirely in uint16_t and then with a uint32_t cast. Print both and explain the difference.
  4. Fixes the signed/unsigned comparison from this lesson so it prints true, without changing the values.

This is a software-only activity.

Deliverables

  • Your program and its output
  • Your hand calculations for the 16-bit and 32-bit millisecond wrap times
  • One or two sentences explaining each surprising result

Knowledge check

Check your understanding

  1. 1. A uint8_t variable holds 200. You add 100 and store the result back in it. What does it hold?
  2. 2. Why do embedded programmers prefer int16_t or int32_t over plain int?
  3. 3. What does the C standard say happens when a signed int overflows?
  4. 4. Which expression correctly converts a 10-bit reading counts (a uint16_t) to millivolts with a 3,300 mV reference?

Go further

C types, sizes and integer overflow — Embedded Systems — Tactiverge