Optimal structure field ordering

Daniel R. Levy levy at ttrdc.UUCP
Mon Jun 27 09:49:36 AEST 1988


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 think you have your Smallie misordered for maximum "portability".  On a
3B20 the program prints:

Biggie is 16 bytes long, but Smallie is only 16 bytes long.

I get better results with:

typedef struct { long l; short s; char buf[5]; char c; } Smallie;

which gives me:

Biggie is 16 bytes long, but Smallie is only 12 bytes long.

Your good result on the Sun-3 is because structs and longs only need be
halfword aligned there.
-- 
|------------Dan Levy------------|  THE OPINIONS EXPRESSED HEREIN ARE MINE ONLY
|    AT&T  Data Systems Group    |  AND ARE NOT TO BE IMPUTED TO AT&T.
|        Skokie, Illinois        | 
|-----Path:  att!ttbcad!levy-----|



More information about the Comp.lang.c mailing list