cpp core · high
Struct Alignment & Padding
Struct layout follows declaration order. Each member must start at an offset that is a multiple of its alignment, so the compiler inserts padding between fields and at the end (rounding sizeof up to a multiple of alignof). Reordering members from largest to smallest alignment eliminates most internal padding — here it shrinks the struct from 12 to 8 bytes.
Members are laid out in declaration order; the compiler pads to honor each member's alignment and rounds the whole struct up to its largest alignment — reorder big->small to shrink sizeof.
The code
struct Bad { // declaration order IS the memory order char a; // offset 0 (1 byte) int b; // needs a 4-byte-aligned offset -> goes to 4 char c; // offset 8}; // sizeof == 12, alignof == 4 (6 bytes wasted)
struct Good { // reordered: largest member first int b; // offset 0 char a; // offset 4 char c; // offset 5}; // sizeof == 8, alignof == 4 (2 trailing pad)
static_assert(sizeof(Bad) == 12);static_assert(sizeof(Good) == 8);What this lesson walks through
- 01Members keep their declared order
- 02char a — alignment 1
- 03int needs a 4-aligned offset
- 04int b lands at offset 4
- 05Trailing padding rounds the size up
- 06Reorder largest -> smallest
- 07Pack hot structs tight
A struct's fields are laid out in the order you declare them. The compiler may leave gaps between them so that each member starts at an address its type can tolerate.
See it animated — step by step, at your own pace
Unlock the full interactive walkthrough of Struct Alignment & Padding and 100+ animated C++ interview lessons.