Home / Learn Embedded C / sizeof and Portable Code
sizeof and Portable Code
Why hardcoding a type's size is risky, and how sizeof keeps code correct across compilers.
What's actually going on
Definition
sizeof(type-or-expression) asks the compiler for the exact byte size of something, at compile time — it never needs to be guessed or hardcoded.
Why you need this
Memory-constrained code frequently needs an exact byte count (for a buffer, a memcpy, or a struct), and hardcoding a number that happens to be right today can silently break on a different compiler or chip.
How it works
sizeof is evaluated by the compiler, not at runtime, so it has zero runtime cost and is always exactly correct for whatever type or variable you ask about.
Where you'll see this
- Buffer sizing
- Portable array-length calculations
Try it
sizeof(array)/sizeof(array[0]) is the standard, portable way to count an array's elements in C.
Try it: comparing type sizes directly
sizeof lets you compute exact byte budgets (like 10 * sizeof(short)) instead of hardcoding a number that might be wrong on a different compiler.
Test what you just read
1. When is sizeof(x) actually computed?
sizeof is a compile-time operator — the compiler already knows every type's size when compiling.