Nasty supprise when using c 'anonymous struct and union' in D with 'static struct'

Steven Schveighoffer schveiguy at gmail.com
Tue Dec 29 14:42:07 UTC 2020


On 12/29/20 7:38 AM, Arjan wrote:
> see https://en.cppreference.com/w/c/language/struct
> 
> It seems the 'static' must NOT be used here to get the equivalent 
> behavior of c, when left in the assertions will fail.
> 
> Is this expected?
> 
> ```
> unittest
> {
> 
> struct W
> {
> align(1):
>      long k;
>      long l;
> }
> 
> struct V
> {
> align(1):
>      union // anonymous union
>      {
>          /*static*/ struct // anonymous structure
>          {
>              long i;
>              long j;
>          }
>          W w;
>     }
>     int m;
> }
> 
> V v1;
> 
> v1.i = 2;
> assert( 2 == v1.w.k );
> v1.w.l = 5;
> assert( 5 == v1.j );
> }
> ```

I added in some printouts of the addresses of the variables.

It appears that if you add static to the struct, it now becomes a static 
member of the union, which means it's not an instance variable, and is 
now a thread-local variable. Its address doesn't even coincide remotely 
with the address of v1.

What is the equivalent behavior for C that you are expecting? The usage 
of "static struct" doesn't appear in that page you linked to.

-Steve


More information about the Digitalmars-d-learn mailing list