Are C unions never padded at the beginning?

匆匆过客 提交于 2019-12-07 07:05:06

问题


Are there any guarantees in the C99 standard that unions will only ever be padded at the end like structs? And relatedly, will the address of the union always be equal to the address of any of its possible members?


回答1:


  1. Yes. As you note, structures never have leading padding. The address of a union always refers to the first element of any component of the union (with suitable casts), so there can't be any padding at the start of a union either.

  2. Yes. Suitably cast, the address of a union is also a pointer to any of the elements within the union.

ISO/IEC 9899:2011

6.7.2.12 Structure and union specifiers

¶15 Within a structure object, the non-bit-field members and the units in which bit-fields reside have addresses that increase in the order in which they are declared. A pointer to a structure object, suitably converted, points to its initial member (or if that member is a bit-field, then to the unit in which it resides), and vice versa. There may be unnamed padding within a structure object, but not at its beginning.

¶16 The size of a union is sufficient to contain the largest of its members. The value of at most one of the members can be stored in a union object at any time. A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa.

¶17 There may be unnamed padding at the end of a structure or union.




回答2:


The standard makes the following guarantee:

6.7.2.11-4: A pointer to a union object, suitably converted, points to each of its members (or if a member is a bit-field, then to the unit in which it resides)

This means that there can be no padding at the beginning of a union.




回答3:


The language specification does not make a direct guarantee about it. However it says

A pointer to a union object, suitably converted, points to each of its members (or if a member is a bitfield, then to the unit in which it resides), and vice versa.

Note that pointer conversion in C language never implies that the numeric value of the pointer (the actual address) is preserved during the conversion. This means that technically it is possible to satisfy this requirement and still have padding at the beginning of the union.

However, there's no reason to have it there. And, quite obviously, there was no intent to introduce that possibility. Especially if you take into account that the language specification explicitly says that there's no padding at the beginning of structs.



来源:https://stackoverflow.com/questions/46815865/are-c-unions-never-padded-at-the-beginning

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!