D issues are now tracked on GitHub. This Bugzilla instance remains as a read-only archive.
Issue 18855 - Behavior of Anonymous Union is Undocumented
Summary: Behavior of Anonymous Union is Undocumented
Status: RESOLVED FIXED
Alias: None
Product: D
Classification: Unclassified
Component: dlang.org (show other issues)
Version: D2
Hardware: x86_64 Linux
: P1 minor
Assignee: No Owner
URL: https://github.com/dlang/dlang.org/pu...
Keywords: pull
Depends on:
Blocks:
 
Reported: 2018-05-13 09:40 UTC by Vijay Nayar
Modified: 2022-07-29 08:08 UTC (History)
2 users (show)

See Also:


Attachments

Note You need to log in before you can comment on or make changes to this issue.
Description Vijay Nayar 2018-05-13 09:40:26 UTC
In the DLang specification here: https://dlang.org/spec/struct.html#AnonUnionDeclaration

It is said that anonymous unions can be declared, but the ramifications of this are never clarified. Those coming from C++ will suspect that it makes the anonymous union members members of the containing object, but for those coming from Java or another language, this behaviour will seem unexplained.

Example below:
```
void main()
{
  import std.stdio;
  struct Bob {
    int a;
    union {  // Anonymous union.
      int b;
      int c;
    }
    union Cat {
      int d;
      int e;
    }
    Cat cat;
  }
	
  Bob bob = Bob(1, 2);
  assert(bob.a == 1);
  assert(bob.b == 2);
  assert(bob.c == 2);
  bob.cat = Bob.Cat(3);
  // assert(bob.d == 3); // ERROR, Bob has no property 'd'.
  assert(bob.cat.d == 3);  // OK
}
```
Comment 1 Dlang Bot 2022-07-27 13:35:35 UTC
@ntrel updated dlang/dlang.org pull request #3355 "[spec/struct] Add 'Union Literals' & 'Anonymous Structs & Unions'" fixing this issue:

- Fix issues 18855 and 21188 - Add 'Union Literals' & 'Anonymous Structs & Unions'
  
  Fix Issue 21188 - Anonymous structs - not described.
  Fix Issue 18855 - Behavior of Anonymous Union is Undocumented.
  
  Fix: Non-overlapping union field data is not default initialized, it is
  zeroed.

https://github.com/dlang/dlang.org/pull/3355