5 ms·
The stuff described on the first part of that page has been supported by GCC for ages. It's useful where structs and unions are deeply nested, e.g.: enum MyS
by pmjordan 16y ago
The stuff described on the first part of that page has been supported by GCC for ages. It's useful where structs and unions are deeply nested, e.g.:
enum MyStructType { MyInt, MyFloat };
struct my_struct
{
enum MyStructType type;
union
{
struct {
int my_int;
} as_int;
struct {
float my_float;
} as_float;
} d;
};
To get to the actual data, in standard C89/99 you need to do this:
struct my_struct* s = /* ... */;
if (s->type == MyInt)
printf("%i\n", s->d.as_int.my_int); /* <- !!!!!! */
else
printf("%f\n", s->d.as_float.my_float); /* <- !!!!!! */
With the extension, the inner union and struct members are added to the outer struct/union's namespace:
enum MyStructType { MyInt, MyFloat };
struct my_struct
{
enum MyStructType type;
union
{
struct {
int my_int;
};
struct {
float my_float;
};
}; /* note: no name */
};
Now the access code is much nicer:
struct my_struct* s = /* ... */;
if (s->type == MyInt)
printf("%i\n", s->my_int); /* <- !!!!!! */
else
printf("%f\n", s->my_float); /* <- !!!!!! */
The second part extends this to typedefs, while the third part, the Plan9 addition (which is presumably the reason for the HN submission) gives you an implicit struct pointer conversion for structs composed of other structs, a bit like C++'s implicit pointer conversion for inheritance. The page has an example of this already:
struct s1 { int a; };
struct s2 { struct s1; };
extern void f1 (struct s1 *);
void f2 (struct s2 *p) { f1 (p); }
This is how you'd normally have to do it:
struct s1 { int a; };
struct s2 { struct s1 my_s1; }; // <- note non-anonymous struct field
extern void f1 (struct s1 *);
void f2 (struct s2 *p) { f1 (&p->my_s1); } // <- my code is always littered with this idiom
All of this might not seem like much, but complicated data structures really aren't a forte of the C syntax. A bit of sugar alleviates at least some of the endless repetition.