| |||
| Home > Compiler Coding Practices > Unaligned fields in structures | |||
For efficiency, fields in a structure are positioned on their natural size boundary. This means that the compiler often inserts padding between fields to ensure that they are naturally aligned.
When space is at a premium, the __packed qualifier
can be used to create structures without padding between fields.
Structures can be packed in the following ways:
The entire struct can
be declared as __packed. For example:
__packed struct mystruct
{
char c;
short s;
} // not recommended
Each field of the structure inherits the __packed qualifier.
Declaring an entire struct as __packed typically
incurs a penalty both in code size and performance.
Individual non-aligned fields within the struct can
be declared as __packed. For example:
struct mystruct
{
char c;
__packed short s; // recommended
}
This is the recommended approach to packing structures.
The same principles apply to unions. You can declare either
an entire union as __packed, or use the __packed attribute
to identify components of the union that are unaligned in memory.