Reading history

Fixed-Width Integers in C: stdint.h and inttypes.h

7 min read 1 views

Use int8_t, uint32_t, int64_t and friends from stdint.h, print them portably with PRId32-style macros, and prevent integer overflow in C.

How big is an int in C? The honest answer is “it depends”. The standard only promises a minimum size, so an int may be 2 bytes on a small microcontroller and 4 bytes on a laptop, and a long is 4 bytes on Windows but 8 on Linux. When the exact size matters, as in file formats, network data or hardware registers, you need the fixed-width integer types from <stdint.h>. This lesson shows how to use them and how to avoid integer overflow.

In this lesson you will learn

  • Why int and long have no fixed size
  • int8_t, uint32_t, int64_t and their limits
  • Printing them correctly with the PRId32-style macros
  • Unsigned wrap-around, and why signed overflow is dangerous
  • Checking for overflow before it happens

You should know data types, ranges of data types and the sizeof operator.

The Fixed-Width Types

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

int main(void) {
    /* Plain int, long: size depends on the system */
    printf("int: %zu bytes, long: %zu bytes, long long: %zu bytes\n",
           sizeof(int), sizeof(long), sizeof(long long));

    /* Fixed-width types: always the same size */
    int8_t   tiny   = -100;
    uint8_t  byte   = 250;
    int32_t  salary = 85000;
    uint64_t views  = 12345678901ULL;
    printf("int8_t %zu, uint8_t %zu, int32_t %zu, uint64_t %zu bytes\n",
           sizeof tiny, sizeof byte, sizeof salary, sizeof views);

    /* Printing them portably with the PRI macros from inttypes.h */
    printf("tiny=%" PRId8 " byte=%" PRIu8 " salary=%" PRId32 " views=%" PRIu64 "\n",
           tiny, byte, salary, views);

    /* Limits */
    printf("INT8_MIN=%d INT8_MAX=%d UINT8_MAX=%d\n", INT8_MIN, INT8_MAX, UINT8_MAX);
    printf("INT32_MAX=%" PRId32 "\n", INT32_MAX);
    printf("UINT64_MAX=%" PRIu64 "\n", UINT64_MAX);

    /* Unsigned values wrap around, which is well defined */
    uint8_t counter = 255;
    counter++;
    printf("uint8_t 255 + 1 = %" PRIu8 "\n", counter);

    /* size_t is the type for sizes and array indexes */
    int marks[] = {72, 88, 95};
    size_t n = sizeof marks / sizeof marks[0];
    printf("array has %zu items; size_t is %zu bytes\n", n, sizeof(size_t));
    return 0;
}

Output

int: 4 bytes, long: 8 bytes, long long: 8 bytes
int8_t 1, uint8_t 1, int32_t 4, uint64_t 8 bytes
tiny=-100 byte=250 salary=85000 views=12345678901
INT8_MIN=-128 INT8_MAX=127 UINT8_MAX=255
INT32_MAX=2147483647
UINT64_MAX=18446744073709551615
uint8_t 255 + 1 = 0
array has 3 items; size_t is 8 bytes
  • The first line was produced on 64-bit Linux, where long is 8 bytes. On 64-bit Windows it is 4 bytes. That is exactly why fixed-width types exist.
  • The name tells you everything: int8_t is a signed 8-bit integer, uint32_t an unsigned 32-bit one. The u means unsigned, and the number is the number of bits.
  • To print them, use the macros from <inttypes.h>. PRId32 expands to the right letters for a 32-bit signed value on that system, and string pasting joins it into the format: "%" PRId32.
  • Each type has limit macros, such as INT8_MAX and UINT64_MAX.
  • Unsigned values wrap around: 255 + 1 in a uint8_t becomes 0. This is well defined, like a car’s odometer rolling over.
  • size_t (printed with %zu) is the unsigned type for sizes and array indexes. sizeof returns it.
TypeRangeTypical use
int8_t / uint8_t−128 to 127 / 0 to 255Bytes, small counters, pixel colours
int16_t / uint16_t−32,768 to 32,767 / 0 to 65,535Audio samples, port numbers
int32_t / uint32_tabout ±2.1 billion / 0 to about 4.3 billionGeneral numbers, IDs, file fields
int64_t / uint64_tabout ±9.2 × 1018 / 0 to about 1.8 × 1019Money in small units, timestamps, big counts

Overflow and How to Prevent It

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

/* Safe addition: check BEFORE adding, because signed overflow is undefined */
bool add_ok(int32_t a, int32_t b, int32_t *out) {
    if ((b > 0 && a > INT32_MAX - b) || (b < 0 && a < INT32_MIN - b))
        return false;
    *out = a + b;
    return true;
}

int main(void) {
    int32_t result;
    int32_t tests[][2] = {{2000000000, 100000000}, {2000000000, 200000000}, {-2000000000, -200000000}};
    for (int i = 0; i < 3; i++) {
        if (add_ok(tests[i][0], tests[i][1], &result))
            printf("%" PRId32 " + %" PRId32 " = %" PRId32 "\n", tests[i][0], tests[i][1], result);
        else
            printf("%" PRId32 " + %" PRId32 " would overflow\n", tests[i][0], tests[i][1]);
    }

    /* Mixing signed and unsigned: -1 becomes a huge unsigned number */
    int32_t minus_one = -1;
    uint32_t one = 1;
    printf("-1 < 1u is %s\n", (uint32_t)minus_one < one ? "true" : "false");
    printf("-1 as uint32_t = %" PRIu32 "\n", (uint32_t)minus_one);

    /* Doing the multiplication in a wider type avoids overflow */
    int32_t price = 150000, qty = 20000;
    int64_t total = (int64_t)price * qty;
    printf("150000 * 20000 = %" PRId64 "\n", total);

    /* Fast and least types: at least N bits, chosen by the system */
    printf("int_least16_t %zu bytes, int_fast16_t %zu bytes\n",
           sizeof(int_least16_t), sizeof(int_fast16_t));
    return 0;
}

Output

2000000000 + 100000000 = 2100000000
2000000000 + 200000000 would overflow
-2000000000 + -200000000 would overflow
-1 < 1u is false
-1 as uint32_t = 4294967295
150000 * 20000 = 3000000000
int_least16_t 2 bytes, int_fast16_t 8 bytes
  • Going past the limit of a signed type is undefined behaviour. The program may print a wrong number, crash, or behave strangely after compiler optimisation. You cannot check afterwards; you must check before adding.
  • add_ok compares against the limit first. If b is positive, the sum fits only when a <= INT32_MAX - b. That subtraction itself can never overflow.
  • Mixing signed and unsigned is a classic trap. In the comparison, −1 is converted to unsigned and becomes 4,294,967,295, so “−1 < 1” turns out false. Keep comparisons between values of the same signedness.
  • 150,000 × 20,000 is 3 billion, too big for int32_t. Casting one side to int64_t before multiplying makes the whole calculation 64-bit.
  • int_least16_t is the smallest type with at least 16 bits. int_fast16_t is the fastest one, which may be bigger, as it is here (8 bytes).

Common Mistakes

  1. Printing int64_t with %d or %ld. It may work on one system and print garbage on another. Use PRId64.
  2. Multiplying before widening: (int64_t)(a * b) overflows first, then casts. Write (int64_t)a * b.
  3. Using unsigned for values that can go negative, such as a difference between two dates.
  4. Looping down with an unsigned index: for (size_t i = n - 1; i >= 0; i--) never ends, because an unsigned value is always ≥ 0.

Practice Exercises

Exercise 1. Which type would you use to store a person’s age, an RGB colour channel, and a bank balance in poisha (1/100 taka)?

Show answer

Age: uint8_t (0–255 is enough). Colour channel: uint8_t (exactly 0–255). Bank balance in poisha: int64_t, because balances can be large and may go negative with an overdraft.

Exercise 2. Write a function bool mul_ok(int32_t a, int32_t b, int32_t *out) that multiplies two values only if the result fits.

Show answer
bool mul_ok(int32_t a, int32_t b, int32_t *out) {
    int64_t wide = (int64_t)a * b;          /* cannot overflow in 64 bits */
    if (wide > INT32_MAX || wide < INT32_MIN) return false;
    *out = (int32_t)wide;
    return true;
}

Two 32-bit numbers multiplied together always fit in 64 bits, so doing the work in a wider type and checking the range is simple and safe.

Frequently Asked Questions

Should I stop using int altogether?

No. int is fine for loop counters and everyday values that stay small. Use fixed-width types when the exact size matters: data written to files or networks, hardware, or values that might grow very large.

Does every system have int8_t and the other exact types?

Almost every modern system does. The standard makes the exact-width types optional for unusual machines, but the “least” and “fast” types, such as int_least8_t, always exist.

Summary

  • <stdint.h> gives types with exact sizes: int8_t to uint64_t.
  • Print them with the macros from <inttypes.h>, such as "%" PRIu64.
  • Unsigned overflow wraps; signed overflow is undefined, so check before you calculate.
  • Widen before multiplying, and avoid mixing signed and unsigned.

Next: C printf Format Specifiers.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *