In standard C, the size of data types like int, long, or short is not fixed; it can change depending on the compiler and the system architecture (e.g., 16-bit, 32-bit, or 64-bit). Fixed-Width Integers solve this problem by providing types that have the exact same size on every system.
To use fixed-width integers, you must include the <stdint.h> header (introduced in the C99 standard). This header defines specific types where the number of bits is guaranteed.
These types follow a naming convention: [u]intN_t, where 'u' stands for unsigned, and 'N' is the number of bits.
| Type | Size (Bits) | Range |
|---|---|---|
int8_t / uint8_t |
8 bits (1 byte) | -128 to 127 / 0 to 255 |
int16_t / uint16_t |
16 bits (2 bytes) | -32,768 to 32,767 / 0 to 65,535 |
int32_t / uint32_t |
32 bits (4 bytes) | -2.1B to 2.1B / 0 to 4.2B |
int64_t / uint64_t |
64 bits (8 bytes) | Huge ranges for large data. |
Printing these types with printf can be tricky because standard specifiers like %d might not match. The inttypes.h header provides macros to print them correctly.
The library also includes "fast" and "least" types for cases where you prioritize speed over exact sizing.
When writing low-level software (like embedded systems or network protocols), using int is dangerous because it could be 16-bit on one chip and 32-bit on another, causing data corruption or overflow bugs.
You can also find the limits of these types using predefined macros like INT32_MAX, INT32_MIN, or UINT8_MAX.