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.

In shortWhy 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

Using sizeof instead of a hardcoded buffer sizeC: edit and run

sizeof(array)/sizeof(array[0]) is the standard, portable way to count an array's elements in C.

Try it: comparing type sizes directly

Using sizeof to compare two types' sizes directlyC: edit and run

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?