Topics / C Programming / Q16
What is the size of an int, and what are fixed-width types?
Short answer: The C standard only fixes minimum ranges: char at least 8 bits, short and int at least 16, long at least 32, long long at least 64. The actual sizes depend on the compiler and target: int is 16 bits on 8-bit AVR and MSP430, and 32 bits on ARM Cortex-M, ARM64 and x86. For hardware registers and data formats use the fixed-width types from <stdint.h>.
Typical data models
| Type | AVR (8-bit) | Cortex-M (ILP32) | ARM64 / x86-64 Linux (LP64) | 64-bit Windows (LLP64) |
|---|---|---|---|---|
char |
8 | 8 | 8 | 8 |
short |
16 | 16 | 16 | 16 |
int |
16 | 32 | 32 | 32 |
long |
32 | 32 | 64 | 32 |
| pointer | 16 | 32 | 64 | 64 |
<stdint.h> types
- Exact width:
int8_t,uint16_t,uint32_t,int64_t— for registers, protocol fields, file formats. - Least:
uint_least16_t— at least 16 bits (portable even to unusual DSPs without 8-bit types). - Fast:
uint_fast16_t— the fastest type with at least 16 bits (often 32 bits on Arm, avoiding extra masking instructions). intptr_t/uintptr_t— an integer that can hold a pointer.size_t(sizes and indexes, unsigned),ptrdiff_t(pointer differences, signed).
printf formats: use <inttypes.h> macros, e.g. printf("%" PRIu32 "\n", x);, because uint32_t is unsigned long on some toolchains and unsigned int on others.
Common bugs from assuming sizes
- Storing a pointer in an
int(breaks on 64-bit). longtimestamps that overflow on ILP32 but not on the PC where tests run.- A loop
for (uint8_t i = 0; i < 300; i++)never ends:iwraps at 255.
Check sizes at compile time: _Static_assert(sizeof(struct header) == 16, "header must be 16 bytes");.