In C++, how does the declaration order of data members change a struct's size, and may the compiler reorder them to save space?
answer
- largest alignment first
- same members, different sizes
- declaration order is fixed
- C++23 dropped the access exception
basics
~20 sPadding depends on which member follows which, so the same members can take 24 or 16 bytes. The compiler may not reorder them; since C++23 every non-static data member is laid out in declaration order, so sorting is your job.
solid answer
~50 sPadding is inserted before a member whose alignment the current offset does not meet, plus tail padding to a multiple of the struct's alignment. `struct Loose { char a; double b; char c; };` needs 7 bytes before `b` and 7 after `c`: `sizeof` 24 on Apple clang 21. `struct Tight { double b; char a; char c; };` needs only 6 bytes of tail padding: 16. The compiler will not do this for you. Non-static data members of non-zero size are allocated so that later members have higher addresses; up to C++20 that was only promised among members with the same access control, and C++23 (P1847R4) made declaration order mandatory for all of them. Reordering can break code that relies on layout, such as `offsetof`, serialization or aggregate initialization order. Clang's `-Wpadded` lists every gap. Sorting by decreasing alignment is the usual fix, trading against grouping fields that are used together.
code
cpp · 15 lines#include <cstdio>
struct Loose { // 1 + 7 padding + 8 + 1 + 7 tail padding
char a;
double b;
char c;
};
struct Tight { // 8 + 1 + 1 + 6 tail padding
double b;
char a;
char c;
};
int main() {
std::printf("alignof(double) = %zu\n", alignof(double));
std::printf("sizeof(Loose) = %zu, sizeof(Tight) = %zu\n", sizeof(Loose), sizeof(Tight));
}go deeper
Know that reordering members can shrink a struct and that putting the largest types first is the usual rule.
Compute interior and tail padding for two orderings, and explain why the compiler must keep declaration order.
Know the C++23 declaration-order rule, use -Wpadded and static_assert to pin optimized layouts, and recognize when a layout must not change because files or other languages depend on it.
Weigh memory savings in bulk data against readability and compatibility, and decide which types get pinned layouts and size checks in review.
## The same members, two sizes With 8-byte-aligned `double` (the case on mainstream 64-bit ABIs and on Apple clang 21 for arm64), compare two orderings of one `double` and two `char`s: | Layout | Offsets | Padding | `sizeof` | |---|---|---|---| | `struct Loose { char a; double b; char c; };` | `a` 0, `b` 8, `c` 16 | 7 bytes before `b`, 7 bytes of tail | 24 | | `struct Tight { double b; char a; char c; };` | `b` 0, `a` 8, `c` 9 | 6 bytes of tail | 16 | Both have alignment 8, so both sizes must be multiples of 8. The difference is that `Loose` pays for a gap in the middle as well as at the end. For one object it is 8 bytes; for a million-element `std::vector<Loose>` it is 8 MB more memory and proportionally more cache traffic. ## The rule of thumb Order members by **decreasing alignment**: 8-byte types first, then 4-byte, 2-byte and 1-byte types. Within that, keep members that are used together near each other. Two caveats: - Arrays and nested structs count by their element's or their own alignment, not their size: `char name[13]` has alignment 1. - The ideal order depends on the ABI. A `long` is 8 bytes on most 64-bit Unix-like systems and 4 bytes on 64-bit Windows, so a layout tuned on one can pad differently on the other. ## Why the compiler will not reorder The class-members clause says that non-variant non-static data members of non-zero size "are allocated so that later members have higher addresses within a class object". That rule has a history worth knowing: 1. Up to C++20, the guarantee applied only to members with the **same access control**; members separated by a `public:` or `private:` label could, in principle, be ordered differently. 2. C++23 adopted **P1847R4**, "Make declaration order layout mandated", and the current wording applies to all such members regardless of access. So the order you write is the order in memory, and a compiler that sorted members to shrink a struct would change observable behaviour: `offsetof` values, the order of aggregate and designated initializers, the bytes written by `memcpy` serialization, and the layout another translation unit or another language sees through a header. ## Tools - Clang's `-Wpadded` reports each gap, such as `padding struct 'Loose' with 7 bytes to align 'b'` and `padding size of 'Loose' with 7 bytes to alignment boundary`. It is noisy across a whole codebase, so it is usually enabled per file or per type. - `static_assert(sizeof(Tight) == 16);` pins a layout you have optimized so a later edit that reintroduces padding fails the build. - `offsetof` prints each member's position in a standard-layout class. ## When not to reorder - **Shared layouts.** A struct mirrored in a file format, a network protocol or a C header has a fixed field order; reordering it breaks compatibility. - **Readability.** Grouping by meaning sometimes matters more than 8 bytes, especially for types that are never stored in bulk. - **Locality.** Splitting rarely used fields away from hot ones can matter more than total padding; that is a performance-layout decision rather than a padding one. - **Bit-fields.** Their packing is largely implementation-defined, so reordering them is not a portable size optimization. ## What interviewers want ## A worked reordering A record type with `bool active; double score; int id; char grade; double weight; short year;` takes 40 bytes on Apple clang 21 for arm64: 7 bytes of padding before the first `double`, 3 before the second and 6 of tail padding. Sorted as `double score; double weight; int id; short year; bool active; char grade;` the same fields take 24 bytes: 16 for the doubles, 4 for the `int`, 2 for the `short`, 2 for the two one-byte fields, and no padding at all. Cutting 40 percent from a type stored by the million is the kind of change interviewers want a candidate to spot from the declaration alone. ## What interviewers want The expected answer computes both sizes, explains interior and tail padding, and gives the sort-by-alignment rule. A stronger one states that the language forbids reordering, notes the C++23 change that removed the access-control exception, and names `-Wpadded` and `static_assert` as the way to keep an optimized layout from drifting.
- Can the order of members change the result of aggregate initialization?Yes. Aggregate initialization fills members in declaration order, so `Loose{ 'x', 1.5, 'y' }` and `Tight{ 1.5, 'x', 'y' }` list values differently, and C++20 designated initializers must also follow declaration order. Reordering members to save padding therefore changes every positional initializer that uses the type, which is one more reason the compiler never does it silently.
- Does sorting members by alignment always give the smallest possible size?For members whose sizes are multiples of their alignments, which covers the fundamental types and most structs, decreasing alignment leaves at most tail padding, so yes in practice. It can still leave tail padding that another field could have filled, and it ignores which fields are used together, so measure with `sizeof` and `-Wpadded` rather than assuming.
- The compiler reorders members automatically to minimize padding.
- Member order affects only readability, never sizeof.
- Putting the smallest members first always gives the smallest struct.
- In C++23, private and public members may still be placed in any order.
- A layout that is tight on one 64-bit platform is tight on every 64-bit platform.
Assumes C++23, where P1847R4 mandates declaration-order layout for all non-static data members; up to C++20 the guarantee covered only members with the same access control.