Valid to assign to field of struct in union?

Johan Engelen via Digitalmars-d digitalmars-d at puremagic.com
Tue Sep 6 05:56:24 PDT 2016


Hi all,
   I have a question about the validity of this code:
```
void main()
{
     struct A {
         int i;
     }
     struct S
     {
         union U
         {
             A first;
             A second;
         }
         U u;

         this(A val)
         {
             u.second = val;
             assign(val);
         }

         void assign(A val)
         {
             u.first.i = val.i+1;
         }
     }
     enum a = S(A(1));

     assert(a.u.first.i == 2);
}
```

My question is: is it allowed to assign to a field of a struct 
inside a union, without there having been an assignment to the 
(full) struct before?

The compiler allows it, but it leads to a bug with CTFE of this 
code: the assert fails.
(changing `enum` to `auto` moves the evaluation to runtime, and 
all works fine)

Reported here: https://issues.dlang.org/show_bug.cgi?id=16471.



More information about the Digitalmars-d mailing list