Does D support anonymous structs?
Derek Parnell
derek at psych.ward
Wed Feb 22 22:26:13 PST 2006
On Wed, 22 Feb 2006 20:58:35 -0800, Sean Kelly wrote:
> C:\code\d>type test.d
> void main()
> {
> struct { int i; } s;
> s.i = 1;
> }
>
> C:\code\d>dmd test
> test.d(3): anonymous struct can only be a part of an aggregate
Yes. This is the rule "can only be a part of an aggregate".
> ------------------------------------
>
> C:\code\d>type test.d
> void main()
> {
> struct S
> {
> union
> {
> struct
> {
> int i1;
> } s1;
> } u;
> }
>
> S s;
> }
The above doesn't work because if you have an anonymous struct/union is
*must not* have a name - that's why its anonymous. Consequently, you can
only have one anonymous aggregate per parent aggregate.
void main()
{
struct S
{
union
{
struct
{
int i1;
};
};
}
S s;
s.i1 = 42; // You refer to anonymous struct members
// by the member id directly.
}
With named stucts, you have to separate the definition and the declaration.
struct S // Definition
{
int i1;
}
S s; // Declaration
s.i1 = 42;
With anonymous structs, the definition *is* the declaration.
struct S
{
int i1;
struct { int i2; } // Both definition and declaration.
}
S s;
s.i1 = 86;
s.i2 = 99;
--
Derek
(skype: derek.j.parnell)
Melbourne, Australia
"Down with mediocracy!"
23/02/2006 5:19:12 PM
More information about the Digitalmars-d
mailing list