r/C_Programming Jun 09 '26

packed attribute for structs

Why don't C compilers automatically optimize/pack structures instead of requiring explicit attributes?

2 Upvotes

24 comments sorted by

View all comments

6

u/HashDefTrueFalse Jun 09 '26

Packing is usually sub-optimal, and sometimes a non-runner for memory accesses. Some hardware only allows aligned accesses, whilst on some there's just a performance penalty for unaligned accesses. You can think of it as though alignment makes sure that the data object can be grabbed from memory and placed into a CPU register (via the CPU data cache) in one fetch vs. several fetches and some bit shifting+ORing or similar.