Bug 11132 – Odd diagnostic with C-style struct initializer when union field is present
Status
RESOLVED
Resolution
FIXED
Severity
normal
Priority
P2
Component
dmd
Product
D
Version
D2
Platform
All
OS
All
Creation time
2013-09-27T15:35:00Z
Last change time
2013-10-05T00:36:26Z
Keywords
diagnostic, pull
Assigned to
nobody
Creator
andrej.mitrovich
Comments
Comment #0 by andrej.mitrovich — 2013-09-27T15:35:22Z
-----
struct S
{
int x;
union
{
int a;
int b;
}
int z;
}
void main()
{
S s = { 1, 2, 3 };
}
-----
$ dmd test.d
test.d(15): Error: variable test.main.s is not a static and cannot have static initializer
A more appropriate diagnostic is emitted when using the regular D-style syntax:
S s = S(1, 2, 3);
test.d(17): Error: overlapping initialization for b
*However*, C (or is it just C++?) supports a special syntax for initializing union fields:
S s = { 1, { 2 }, 3 };
But the above is an error in D:
test.d(17): Error: a struct is not a valid initializer for a int
I don't know if we want to support this. But we at least have to fix the diagnostic in the first example.
Comment #1 by andrej.mitrovich — 2013-09-27T15:39:07Z
In case you're wondering, I've ran into it while porting this code:
-----
struct STGMEDIUM
{
DWORD tymed;
union
{
HBITMAP hBitmap;
PVOID hMetaFilePict;
HENHMETAFILE hEnhMetaFile;
HGLOBAL hGlobal;
LPWSTR lpszFileName;
LPSTREAM pstm;
LPSTORAGE pstg;
}
LPUNKNOWN pUnkForRelease;
}
STGMEDIUM stgmed = { TYMED.TYMED_HGLOBAL, { 0 }, 0 };
-----
Speaking of which, what is a union field initialized to in D? I mean, what does .init equal to for multiple types? Is it just the bit-pattern zero?
(In reply to comment #1)
> Speaking of which, what is a union field initialized to in D?
It's supposed to be set to the .init of its first field, and any remaining bytes set to 0.