union default initialization values

Nick Treleaven nick at geany.org
Wed Dec 6 12:38:35 UTC 2023


On Tuesday, 5 December 2023 at 19:47:38 UTC, confuzzled wrote:
> On 12/6/23 4:28 AM, Adam D Ruppe wrote:
>> On Tuesday, 5 December 2023 at 19:24:51 UTC, confuzzled wrote:
>>> Given the following union
>>>
>>> union F
>>> {
>>>     double x;
>>>     struct {
>>>         ulong lo;
>>>         ulong hi;
>>>     }
>>> }
>> 
>> The default value of this would be `double.init`, since the 
>> first member of the union is a `double`, which is a kind of 
>> NaN. This is non-zero.
>> 
>
> Correct. So I expected a NaN output for x. However, I wasn't 
> expecting lo == 13835058055282163712 and hi == 32767 where x is 
> of type real, or lo == 9221120237041090560 and hi = 0 where x 
> is of type double. Based on the default initialization rules, I 
> expected both lo and hi to have a value of zero regardless if x 
> is of type double or real. This is what I'm trying to 
> understand, how are these values derived?

ulong.sizeof is 8, like double.sizeof. So F.init.lo should have 
the same bit pattern as F.init.x because they share storage 
exactly. F.init.hi should be 0 and it is on my system. (*"If the 
union is larger than the first field, the remaining bits are set 
to 0"*). I don't know why you don't get zero for that.


More information about the Digitalmars-d-learn mailing list