Re: structure layout question



Stephen Sprunk wrote:
"kyle york" <kyork@xxxxxxxxx> wrote in message
news:1172772376.435029@xxxxxxxxxxxxxxxxxxxxxxxxxxx

Why does the C standard require the members of a structure not be
re-ordered (6.2.5.20)? Padding is allowed, and platform dependent,
which means one cannot rely on the exact layout anyway, so what's
the point?

Without this restriction the compiler could layout the structure in the
most efficient way possible, for some definition of efficient. It would be
easy enough to turn this reordering off with a compiler specific pragma as
is often done with padding.


The standard's wording guarantees that two structs defined with the same
initial elements will be laid out the same way in memory and that, as long
as you access only common members, they will be interchangeable. It also
means that any later elements that are not common will be laid out _after_
the common ones, not interspersed with the common ones.

If a compiler was allowed to reorder the elements, these properties would
not hold and a lot of code would break.

Just to add to this, the above guarantee is important where structures
are members of a union and the first member or members are used to
identify the appropriate type. One example of this is the X-windows
event object which is a union of all possible event structs.

--
Ian Collins.
.



Relevant Pages