Reducing space wasted on padding by rearranging variables is another way to reduce your program's space requirement.
With the exception of packed decimal data types, variables are padded the same in both C and C++:
A C packed decimal type variable can be 1-32 bytes in size.
A C++ packed decimal type variable can be 1-16 bytes in
size.
By rearranging variables, wasted space created by padding can be minimized, as shown in Figure 50.
Figure 50. Example of Minimizing Padding by Rearranging Variables
class ItemT { char *name; // 16 bytes. int number; // 4 bytes plus 12 bytes. char *address; // 16 bytes. double value; // 8 bytes plus 8 bytes. char *next; // 16 bytes. short rating; // 2 bytes plus 14 bytes. char *previous; // 16 bytes. _DecimalT<25,5> tot_order; // 13 bytes plus 3 bytes. int quantity; // 4 bytes. _DecimalT<12,5> unit_price; // 7 bytes plus 5 bytes. char *title; // 16 bytes. char flag; // 1 byte plus 15 bytes. } itemT;
The ItemT class can be rearranged as: class ItemT { char *name; // 16 bytes char *address; // 16 bytes char *next; // 16 bytes char *previous; // 16 bytes char *title; // 16 bytes double value; // 8 bytes int quantity; // 4 bytes int number; // 4 bytes short rating; // 2 bytes char flag; // 1 byte _DecimalT<25,5> tot_order; // 13 bytes _DecimalT<12,5> unit_price; // 7 bytes plus 9 bytes } itemT;
|
As a general rule, the space used for padding can be minimized if 16-byte variables are declared first, 8-byte variables are declared second, 4 byte variables are declared third, 2-byte variables are declared fourth, and 1-byte variables are declared fifth. _DecimalT template class objects should be declared last, after all other variables have been declared. The same rule can be applied to structure or class definitions.
To show the layout (including padding) of module structures, in both packed and normal alignment, use either the *AGR or the *STRUCREF compiler option.
(C) Copyright IBM Corporation 1992, 2005. All Rights Reserved.