5.36 Unaligned fields in structures

You can use the __packed qualifier to create unaligned fields in structures. This saves space because the compiler does not need to pad fields to their natural size boundary.

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, you can use the __packed qualifier 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.

Note

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.

Related concepts
5.37 Performance penalty associated with marking whole structures as packed
5.40 Comparisons of an unpacked struct, a __packed struct, and a struct with individually __packed fields, and of a __packed struct and a #pragma packed struct
Related reference
10.12 __packed
10.95 #pragma pack(n)
Non-ConfidentialPDF file icon PDF versionARM DUI0472J
Copyright © 2010-2013 ARM. All rights reserved.