Course contentsShow
← C
Lesson 944 of 1,21913. Advanced CFree lesson

Sizes of `int` across different architectures

Sizes of int across different architectures

What you'll learn: Why the int data type changes size depending on your hardware and why you shouldn't assume it is always 32 bits.

The Shrinking and Growing Integer

In many modern programming languages, an integer is a fixed size. In C, however, the int is designed to be the "natural" size for the processor you are targeting. Think of it like a "standard shipping box." On a massive cargo ship (a 64-bit server), the standard box is large. On a small delivery bike (an 8-bit microcontroller), that same "standard" box must be much smaller to fit on the frame.

The C standard only guarantees that an int will be at least 16 bits. Beyond that, the compiler chooses a size that allows the CPU to process math as efficiently as possible.

Where the Trap Lies

If you write code on a modern PC, your int is almost certainly 32 bits, allowing you to store numbers up to about 2.1 billion. However, if you take that same code and compile it for an older embedded system (like an Arduino Uno), the int drops to 16 bits. Suddenly, your maximum value is only 32,767. If your code tries to store 40,000 in that variable, it will overflow, leading to bugs that are incredibly hard to track down.

Checking Your Environment

You can use the sizeof operator to see how your current architecture views an integer. This operator returns the size in bytes (where 1 byte is usually 8 bits).

#include <stdio.h>

int main() {
    // sizeof returns size in bytes
    printf("On this machine, an int is %zu bytes.\n", sizeof(int));
    printf("That means it is %zu bits wide.\n", sizeof(int) * 8);
    
    return 0;
}

If you run this on a 64-bit Linux laptop, you will likely see 4 bytes (32 bits). If you ran it on a 1980s-era computer, you would see 2 bytes (16 bits).

Writing Portable Code

Because the size of int is "implementation-defined," you should never assume it has a specific capacity. If you absolutely need a variable that is exactly 32 bits regardless of the computer it runs on, advanced C programmers use specific headers like <stdint.h>, but understanding the fluid nature of the basic int is the first step toward writing software that works everywhere.

Key takeaway

The size of int is not fixed by the C language; it changes to match the hardware's efficiency, usually ranging from 16 to 32 bits.