Union copy

Ali Çehreli acehreli at yahoo.com
Wed Oct 23 11:07:37 PDT 2013


On 10/21/2013 07:47 PM, "Luís Marques" <luis at luismarques.eu>" wrote:

 > Consider the following on a 32-bit system:
 >
 >      union Foo
 >      {
 >          struct
 >          {
 >              void* v;
 >              int i;
 >          }
 >
 >          double d;
 >      }
 >
 >      static assert(Foo.sizeof == 8);
 >
 >      void copy(Foo* a, Foo* b)
 >      {
 >          version(one)
 >          {
 >              a.v = b.v;
 >              a.i = b.i;
 >          }
 >          version(two)
 >          {
 >              a.d = b.d;
 >          }
 >      }
 >
 > Is there a difference between version one and version two? I was getting
 > erroneous copies with version two on Linux and Windows, while it worked
 > fine on OS X. Does it make a difference if the double is a NaN?

If D's unions are like C's and C++'s, then it is not defined what 
happens when accessing members of the union that are not active.

Either the anonymous struct or 'd' above is active, so only that member 
can be accessed.

Ali



More information about the Digitalmars-d mailing list