What are alignment and padding, and how do they affect the size of a struct?
Last updated
Alignment requires an object's address to be a multiple of some value. Padding is filler bytes the compiler inserts between members and at the end to satisfy it.
So a struct can exceed the sum of its members, and ordering members largest to smallest minimizes padding (e.g. 12 vs. 8 bytes).
Inspect with
alignof, set withalignas, and reduce with#pragma pack(at a performance/portability cost).
- https://learn.microsoft.com/ka-ge/cpp/error-messages/compiler-warnings/compiler-warning-level-4-c4121?view=msvc-150
- https://learn.microsoft.com/en-us/cpp/cpp/alignment-cpp-declarations?view=msvc-170
- https://learn.microsoft.com/en-us/windows/win32/midl/c-compiler-packing-issues
- https://learn.microsoft.com/en-us/cpp/c-language/alignment-c?view=msvc-170