Optimal structure field ordering

Mark Stevans mark at navtech.uucp
Sat Jun 25 06:23:38 AEST 1988


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



More information about the Comp.lang.c mailing list