Why is my union's size bigger than I expected?

前端 未结 5 1689
滥情空心
滥情空心 2021-01-18 06:13

When I print the size of a union like this:

union u {
  char c[5];
  int i;
} un;

using this:

int _tmain(int argc, _TCHAR*          


        
5条回答
  •  失恋的感觉
    2021-01-18 06:45

    The alignment of your union must be the largest alignment of any of its members. This is 4. Therefore, the size of the union must be aligned to that size. It could have been 5 (as c is the largest member of the union), but because the alignment of the union as a whole is 4, the size of the union is padded to 8.

    Note that this is just for VC++. The standard does not specifically require it. Though it does allow implementations to pad types as needed, which VC++ does. GCC could do something different, and there could be compile-time switches you could employ to change this behavior.

提交回复
热议问题