cgccstructsizeof

Struct Padding Optimization in C


#include <stdio.h>

struct X
{
    short s; 
    int i; 
    char c;
};

struct Y
{
    int i;
    char c;
    short s;
};

struct Z
{
    int   i;
    short s;
    char  c;
};

int main() {
    printf("%lu %lu %lu\n", sizeof(struct X), sizeof(struct Y), sizeof(struct Z));
    return 0;
}

The above code returns

12 8 8

demonstrating that a structure's size depends on the order its members are declared. Are there any compiler settings to optimally reorder these declarations (for minimum struct size)? What are some general rules of practice that ensure optimal padding as projects scale?


Solution

  • Are there any compiler settings to optimally reorder these declarations (for minimum struct size)?

    No. C allows programs to rely on and be sensitive to structure member order. Compilers are not free to reorder structure members.

    What are some general rules of practice that ensure optimal alignment

    Generally speaking, you can minimize the padding in structure layouts by ordering members by decreasing alignment requirement.

    Many compilers also provide extensions that enable you reduce or eliminate structure padding at the possible cost of reduced performance arising from misaligned access to members. These extensions are not portable across compilers, however, and they are moot on platforms where misaligned access produces hard errors instead of mere performance penalties.