sizeof union giving unexpected results

Viewed 66

I have read that the sizeof union gives the largest size of member in the union.But when i do this:i'm getting unexpected results:

#include <iostream>

using namespace std;
union RecordType 
{
    int arr[9];
    double x;
};
int main()
{
    RecordType t;
    cout << sizeof(t);   //output is 40,instead of 36 (9*4bytes each)
}

why is the size 40 instead of 36 and even if i change the array to "int arr[10]",then sizeof gives the output as 40 (same as in the case of "int arr[9]),whats internally happening here?

1 Answers

Because double is a 64-bit type on your backend, the compiler will pad the size of the union with additional 32 bits or 4 bytes to align the ints and double. This way the union is aligned to 64 bits, regardless of what member is active.

If you created a union with a float instead, it would most likely have a size of 36 because no such alignment is necessary.

union U 
{
    int arr[9];
    float x;
};

Note that this behavior is implementation defined and it is theoretically possible that a double is 32 bits large as well. So you should never rely on it.

Related