Bug 18855 – Behavior of Anonymous Union is Undocumented
Status
RESOLVED
Resolution
FIXED
Severity
minor
Priority
P1
Component
dlang.org
Product
D
Version
D2
Platform
x86_64
OS
Linux
Creation time
2018-05-13T09:40:26Z
Last change time
2022-07-29T08:08:22Z
Keywords
pull
Assigned to
No Owner
Creator
Vijay Nayar
Comments
Comment #0 by madric — 2018-05-13T09:40:26Z
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 by dlang-bot — 2022-07-27T13:35:35Z
@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