Padding in union is present or not

2019-01-23 18:26发布

问题:

Hello all,
I want to know whether union uses padding?
since the size of union is the largest data member size, can there be padding at the end?

回答1:

since the size of union is the largest data member size

That need not be true. Consider

union Pad {
    char arr[sizeof (double) + 1];
    double d;
};

The largest member of that union is arr. But usually, a double will be aligned on a multiple of four or eight bytes (depends on architecture and size of double). On some architectures, that is even necessary since they don't support unaligned reads at all.

So sizeof (union Pad) is usually larger than sizeof (double) + 1 [typically 16 = 2 * sizeof (double) on 64-bit systems, and either 16 or 12 on 32-bit systems (on a 32-bit system with 8-bit char and 64-bit double, the required alignment for double may still be only four bytes)].

That means there must then be padding in the union, and that can only be placed at the end.

Generally, the size of a union will be the smallest multiple of the largest alignment required by any member that is not smaller than the largest member.



回答2:

Union when we use with primitive types inside it

union
{
    char c;
    int x;
}

It seems like it doesn't use padding because the largest size data is anyway is aligned to boundary.

But when we nest a structure within union it does.

    union u
    {
        struct ss
        {
            char s;
            int v;
        }xx;
    }xu;

It resulted in size 8.

so answer for your question is PADDING is persent in UNION.