Can a C++ compiler re-order elements in a struct
Solution 1:
It normally can't reorder elements, no.
An exception is if there's an access specifier separating them:
struct Foo {
A a;
B b;
C c;
private:
D d;
E e;
F f;
};
a
, b
and c
are guaranteed to be stored in this order, and d
, e
and f
are guaranteed to be stored in order. But there is no guarantees about where a
, b
and c
are stored relative to d
, e
and f
.
Another thing to keep in mind is that the compiler can insert as much padding as it likes, even if it doesn't reorder anything.
Here's the relevant part of the standard:
Section 9.2.12:
Nonstatic data members of a (non-union) class declared without an intervening access-specifier are allocated so that later members have higher addresses within a class object. The order of allocation of nonstatic data members separated by an access-specifier is unspecified (11.1)"
Solution 2:
It can't, see Automated field re-ordering in C structs to avoid padding and Why doesn't GCC optimize structs? for further information.
I don't know what you mean with "reversed", perhaps you should add some code and the output.