struct element orderin vs. alignment.

Kenneth Almquist ka at hou3c.UUCP
Sat Jan 12 17:47:27 AEST 1985


There are two problems with using unions to deal with elements shared
between more than one structure.  As an example, consider the System V
message system call.  Each message begins with a long integer specifying
the message type; the contents of the rest of the message are left to
the applications programmer.  Thus if we used a union to declare these
messages, we would have:
	struct message {
		long m_type;
		union {
			struct msg1 msg1;
			struct msg2 msg2;
			...
			struct msgn msgn;
		} m_union;
	};

Two considerations make this impractical.  One is administrative; every
time a new program was written using the message system call, the union
would grow and the kernel would have to be recompiled (especially tough
for folks with binary only licenses).  The second problem is technical;
there is no portable way to allocate only the amount of memory needed
for a given message.  Allocating "sizeof(struct message)" bytes for each
message may be intolerably inefficient.

It is in part for these reasons that C compilers are not allowed to re-
order structure members.  Currently messages can be handled conveniently
by declaring structures that will begin with a long since C will leave the
type at the beginning of the structure where the programmer put it.

> > >Having two structs
> > >with the same initial set of elements -- and trusting them to stay
> > >that way, even through your novice programmer's "fixes" and the new
> > >A. E. Neumann C Compiler XXX -- isn't all that reliable.

A novice programmer or a nonworking compiler can break any code.  I am
not convinced that sharing structure elements is an exceptionally
confusing practice (at least not by C standards :-)).
					Kenneth Almquist



More information about the Comp.lang.c mailing list