Course contentsShow
← C
Lesson 86 of 1,2192. Variables and TypesFree lesson

Fixed-width types from `<stdint.h>`

Fixed-width types from <stdint.h>

What you'll learn: How to use standard integer types that stay exactly the same size regardless of which computer runs your code.

The problem with "Standard" integers

In C, basic types like int or long are a bit like "medium" coffee cups: their actual volume depends on which shop you visit. On an older 16-bit system, an int might only hold numbers up to 32,767. On a modern PC, it usually holds billions.

If you are writing a program that needs to store a specific piece of data—like a color code that must be exactly 8 bits or a large ID number that must be 64 bits—using int is a gamble. Your program might work on your laptop but crash on a smaller device because the "cup" wasn't big enough.

The solution: <stdint.h>

To fix this, C provides a library called <stdint.h>. It introduces "fixed-width" types. Their names tell you exactly what they are and how much space they take up, no matter what hardware you use.

The names follow a simple pattern: type_size_t.

  • int8_t: A signed 8-bit integer.
  • uint16_t: An unsigned (positive only) 16-bit integer.
  • int32_t: A signed 32-bit integer.
  • uint64_t: An unsigned 64-bit integer.

The u stands for "unsigned," the number is the number of bits, and the _t is a convention standing for "type."

Using fixed-width types in code

Using these types makes your code predictable and professional. It tells other programmers exactly how much data you expect to handle.

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

int main() {
    // This will ALWAYS be 8 bits (1 byte)
    // Range: 0 to 255
    uint8_t game_level = 25;

    // This will ALWAYS be 32 bits (4 bytes)
    // Range: -2,147,483,648 to 2,147,483,647
    int32_t player_score = 150500;

    // This will ALWAYS be 64 bits (8 bytes)
    // Used for massive numbers
    uint64_t world_population = 8000000000ULL;

    printf("Level: %u, Score: %d\n", game_level, player_score);
    
    return 0;
}

Why use them?

Think of fixed-width types as a specialized toolset. While a regular int is fine for simple loops, you should use <stdint.h> whenever you are saving data to a file, sending data over a network, or working with hardware where every single bit counts. It ensures that your "medium" cup is the same size everywhere in the world.

Key takeaway

Use <stdint.h> types like int32_t or uint8_t when you need guaranteed, consistent variable sizes across different computers.