Here's what C and C++ compilers must do to keep structure members aligned.
Rearranging members to reduce padding
You can reduce the size of each widget by rearranging the members to reduce the number of padding bytes. Specifically, you can rearrange the member declarations so that the char members m1 and m3 are adjacent to each other, as in:
struct widget
{
char m1;
char m3;
int m2;
};
In this case, the compiler will add only two padding bytes, as if you had declared widget as:
struct widget
{
char m1;
char m3;
char padding[2];
int m2;
};
Consequently, sizeof(widget) would be only eight, rather than 12. (Again, I'm calculating these sizes assuming an int is a 4-byte object aligned to an address that's a multiple of four. The sizes could be different on a machine with different object sizes and alignment requirements.)
You can rearrange widget's members in other ways to reduce the number of padding bytes. For example, defining widget as:
struct widget
{
int m2;
char m1;
char m3;
};
also reduces the number of padding bytes to two and sizeof(widget) to eight.
A Standard C compiler won't rearrange the members of a structure automatically to reduce the structure's size. According to the Standard: "Within a structure object, the non-bit-field members ... have addresses that increase in the order in which they are declared." This effectively prohibits compilers from rearranging structure members from the order in which they're declared.
Class padding in C++
A C++ class is a generalization of a C structure. For the most part, C code that defines and uses structures behaves the same when compiled and executed as C++.
A C++ class can have elements that a C structure cannot, such as access specifiers (public, protected, and private), member functions, static data members, and base classes. Some of these elements alter the physical layout of class objects and complicate the rules for padding. Those rules will be the subject of my next column.
Thanks to Joel Saks for all his help.
Dan Saks is president of Saks & Associates, a C/C++ training and consulting company. For more information about Dan Saks, visit his website at www.dansaks.com. Dan also welcomes your feedback: e-mail him at dan@dansaks.com. For more information about Dan click here .
Endnotes:
1. Saks, Dan, "Deallocating objects vs. deallocating storage," Embedded Systems Design, March 2009, p. 9.
2. ISO/IEC Standard 9899:1999, Programming languages--C.
3. Saks, Dan, "Tag vs. Type Names," Embedded Systems Programming, October 2002, p. 7.
4. ISO/IEC Standard 14882:2003(E), Programming languages--C++.