union.sizeof

ketmar via Digitalmars-d-learn digitalmars-d-learn at puremagic.com
Sun Mar 26 00:18:14 PDT 2017


zabruk70 wrote:

> On Sunday, 26 March 2017 at 06:45:13 UTC, ketmar wrote:
>> yes. you have a typo in second `writefln`: S1 instead of S2. ;-)
>
> thank you.
> another question, related to my first post:
>
> why size of S2.b1 and S2.b2 still 3, not 4?
>
> am i right: then align applied to members, compiler not change size of 
> members, just make padding, so CONTAINER size changes?

yes. compiler is not allowed to mess with data types of the known size. ;-) 
and you are right: it doesn't have to. it just inserts dummy anonymous (and 
unused) bytes into struct/union to satisfy alignment requirements.


> if so (because size of S2.b1 and S2.b2 still is 3 in my code),
> then adding align(1) outside of union must not change zise of union, but 
> size of some comainer more upper level.

nope, it changes size of the union itself. padding bytes *are* included in 
union, so `myunion.sizeof` includes 'em too.

i.e. what compiler does (roughly) is inserting anonymous fields of the 
appropriate size *into* the container. for "inner" aligning compiler 
inserts anonymous fields *between* other fields. for "outer" aligning 
compiler just appends anonymous field at the *end* of a data type, so data 
type size will met align requirements.


More information about the Digitalmars-d-learn mailing list