Path: utzoo!attcan!uunet!husc6!uwvax!dogie!uwmcsd1!ig!agate!ucbvax!decwrl!spar!navtech!mark
From: mark@navtech.uucp (Mark Stevans)
Newsgroups: comp.lang.c
Subject: Optimal structure field ordering
Message-ID: <163@navtech.uucp>
Date: 24 Jun 88 20:23:38 GMT
Organization: Navigation Technologies Corp., Sunnyvale, CA.
Lines: 34

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.

					Mark "Speedy" Stevans
					spar!navtech!mark