user8797071
user8797071

Reputation: 43

Are C unions never padded at the beginning?

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?

Upvotes: 4

Views: 177

Answers (3)

AnT stands with Russia
AnT stands with Russia

Reputation: 320699

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.

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726967

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.

Upvotes: 2

Jonathan Leffler
Jonathan Leffler

Reputation: 754790

  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.

Upvotes: 3

Related Questions