Path: utzoo!utgpu!water!watmath!clyde!att!ttrdc!levy
From: levy@ttrdc.UUCP (Daniel R. Levy)
Newsgroups: comp.lang.c
Subject: Re: Optimal structure field ordering
Summary: not yet optimum!
Message-ID: <2775@ttrdc.UUCP>
Date: 26 Jun 88 23:49:36 GMT
References: <163@navtech.uucp>
Organization: AT&T, Skokie, IL
Lines: 37

In article <163@navtech.uucp>, mark@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-----|