gcc: Unnamed Fields
1
1 6.62 Unnamed Structure and Union Fields
1 =======================================
1
1 As permitted by ISO C11 and for compatibility with other compilers, GCC
1 allows you to define a structure or union that contains, as fields,
1 structures and unions without names. For example:
1
1 struct {
1 int a;
1 union {
1 int b;
1 float c;
1 };
1 int d;
1 } foo;
1
1 In this example, you are able to access members of the unnamed union
1 with code like 'foo.b'. Note that only unnamed structs and unions are
1 allowed, you may not have, for example, an unnamed 'int'.
1
1 You must never create such structures that cause ambiguous field
1 definitions. For example, in this structure:
1
1 struct {
1 int a;
1 struct {
1 int a;
1 };
1 } foo;
1
1 it is ambiguous which 'a' is being referred to with 'foo.a'. The
1 compiler gives errors for such constructs.
1
1 Unless '-fms-extensions' is used, the unnamed field must be a structure
1 or union definition without a tag (for example, 'struct { int a; };').
1 If '-fms-extensions' is used, the field may also be a definition with a
1 tag such as 'struct foo { int a; };', a reference to a previously
1 defined structure or union such as 'struct foo;', or a reference to a
1 'typedef' name for a previously defined structure or union type.
1
1 The option '-fplan9-extensions' enables '-fms-extensions' as well as
1 two other extensions. First, a pointer to a structure is automatically
1 converted to a pointer to an anonymous field for assignments and
1 function calls. For example:
1
1 struct s1 { int a; };
1 struct s2 { struct s1; };
1 extern void f1 (struct s1 *);
1 void f2 (struct s2 *p) { f1 (p); }
1
1 In the call to 'f1' inside 'f2', the pointer 'p' is converted into a
1 pointer to the anonymous field.
1
1 Second, when the type of an anonymous field is a 'typedef' for a
1 'struct' or 'union', code may refer to the field using the name of the
1 'typedef'.
1
1 typedef struct { int a; } s1;
1 struct s2 { s1; };
1 s1 f1 (struct s2 *p) { return p->s1; }
1
1 These usages are only permitted when they are not ambiguous.
1