How does structure member ordering affect the struct's size, and how can you minimize padding?
Poor ordering scatters padding between members; ordering members from largest/strictest alignment to smallest packs them tightly and shrinks the struct.
* Member ordering changes padding: declare fields in decreasing alignment order to shrink the struct. *
Because each member must start at an aligned offset, a small member followed by a larger one forces padding in between. Reordering can eliminate that gap:
struct S1 {
char c; // offset 0
int i; // offset 4 -> 3 bytes of padding after c!
char d; // offset 8
}; // size 12 (with trailing padding)
| c |pad|pad|pad| i | d |pad|pad|pad|
0 1 2 3 4 5 6 7 8 9 10 11
Just reordering the same three members:
struct S2 {
int i; // offset 0
char c; // offset 4
char d; // offset 5
}; // size 8 (only 2 trailing pad bytes)
Rule of thumb: declare members in decreasing alignment order (8-byte types, then 4, then 2, then 1). It clusters the small members together so they share the leftover space instead of each forcing its own gap.
Why it matters: in large arrays of structs, those wasted bytes multiply — trimming struct S1 (12 → 8) saves a third of the memory and improves cache behavior.
Go deeper:
Data structure alignment (Wikipedia) — how alignment and padding drive the struct's size.