Optimal structure field ordering

Mark Stevans mark at navtech.uucp
Mon Jun 27 16:44:04 AEST 1988


In article <2775 at ttrdc.UUCP> levy at ttrdc.UUCP (Daniel R. Levy) writes:
<In article <163 at navtech.uucp>, mark at navtech.uucp (Mark Stevans) writes:
<# Due to the alignment requirements of various processor architectures, the
<# declared order of fields within a C structure can significantly effect the
<# space required to store the structure.  The easy way to save space on almost
<# all C implementations is to sort your structure fields in order of descending
<# size of the field type.  For arrays, just use the base type.
<# A brief example.  The following program:
<# 	typedef struct { char buf[5]; short s; char c; long l; } Biggie;
<# 	typedef struct { short s; long l; char buf[5]; char c; } Smallie;
<# 	main()
<# 	{
<# 		printf("Biggie is %d bytes long, but Smallie is only %d bytes long.\n",
<# 				sizeof (Biggie), sizeof (Smallie));
<# 	}
<# When compiled and run on a Sun-3/50 produces the output:
<# 	Biggie is 14 bytes long, but Smallie is only 12 bytes long.
<I get better results with:
<typedef struct { long l; short s; char buf[5]; char c; } Smallie;

How goofy can I get?  My example doesn't properly follow my proposed rule!
Just goes to prove the old adage: avoid comments, since they might conflict
with your code.  Thanks for the correction, DRL.  But anyhows, what do y'all
think of the rule itself:

	"The space requirement of any given C structure may be easily
	optimized by reorganizing the structure fields in order of decreasing
	base type size."

Some responder pointed out correctly that there is no guarantee in the C
language that the compiler will preserve your field ordering -- but I wouldn't
worry about that.  I have yet to see a C compiler that did any reordering of
structure fields.  It would make it a challenge to examine structures through
"adb"!  Perhaps some compilers put the elements in reverse order, but that's
about as strange as reality currently gets.

						Mark "Shorty" Stevans



More information about the Comp.lang.c mailing list