C Programming · Interview question

What does __attribute__((packed)) do, and what's the cost?

A strong answer

It tells the compiler to remove all padding from a struct, laying members out back-to-back so sizeof equals the exact sum of the members and offsets match a byte-exact external layout, useful for parsing a network packet or a file format where the bytes are defined by a spec, not by your CPU's alignment. The cost is unaligned access: once members no longer sit on their natural boundaries, the compiler must read/write them in a way that tolerates misalignment. On x86 that's just slower; on a Cortex-M0/M3, a normal word load from an unaligned address faults, so the compiler emits byte-by-byte access sequences, which are significantly slower and larger. So packed is the right tool for byte-exact interchange formats but the wrong tool for performance-sensitive in-memory structures, there you want natural alignment.

What a weak answer sounds like

You know the answer. Do you know what gets you dinged?

Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.

From the lesson

Structs, Unions & Bitfields

Group related data, overlay the same bytes two ways, and pack flags into bits, plus the padding and alignment rules that decide sizeof and bite packet parsing.

More Structs, Unions & Bitfields questions

Browse all 472 interview questions