struct element orderin vs. align

Morris M. Keesan keesan at bbncca.ARPA
Sat Jan 19 03:09:14 AEST 1985


------------------------------------------------------
> > >Sigh,
> > >        until you give me a subclass mechanism that ensures that the
> > >representation of two data types share a common prefix, I'll rely on this
> > >compiler hack.
> > 
> > You already have it:
> > 
> > struct {
> > 	  common part;
> > 	  union {
> > 		  distinct part1;
> > 		  distinct part2;
> > 		  ...
> > 	  };
> > };
> > The distinct parts can of course be structures.
> > This is the only guaranteed portable way to do this.
> 
> Nope; you're only guaranteed a common portion, which might or might not be
> a prefix.  If some one really needs certain fields mapped to the beginning
> of a structure, they have to take advantage of knowing how the compiler will
> map the data.  If a person can depend on "part" being at the beginning of
> that struct, then they can also depend on the ordering in every structure.
> 
> This is a very hard problem -- assuming that one wants a correct solution.
> 
> -- Norman Diamond

Maybe I missed something, and we're talking about some hypothetical language
which is not C.  From the C Reference Manual, section 8.5 (page 196 of K&R):

    Within a structure, the objects declared have addresses which increase
    as their declarations are read left-to-right.  Each non-field member
    of a structure begins on an addressing boundary appropriate to its type;
    therefore, there may be unnamed holes in a structure.

This seems to me to guarantee that the common portion above is a prefix, and
also to guarantee the ordering in every structure, although it does not
guarantee that actual offsets are portably consistent.  Any compiler which does
not "map the data" with "part" being at the beginning of the struct is
incorrect, or is compiling a different language than C.
-- 
			    Morris M. Keesan
			    {decvax,linus,ihnp4,wivax,wjh12,ima}!bbncca!keesan
			    keesan @ BBN-UNIX.ARPA



More information about the Comp.lang.c mailing list