I can do this in c++/g++:
struct vec3 { union { struct { float x, y, z; }; float xyz[3]; }; };
Then,
vec3 v; assert(&v.xyz[0] == &v.x); assert(&v.xyz[1] == &v.y); assert(&v.xyz[2] == &v.z);
will work.
How does one do this in c with gcc? I have
typedef struct { union { struct { float x, y, z; }; float xyz[3]; }; } Vector3;
But I get errors all around, specifically
line 5: warning: declaration does not declare anything line 7: warning: declaration does not declare anything
An anonymous union is not a type; it defines an unnamed object. The member names of an anonymous union must be distinct from other names within the scope in which the union is declared. You can use member names directly in the union scope without any additional member access syntax.
The anonymous unions and structures are unnamed unions and structures. As they have no names, so we cannot create direct objects of it. We use it as nested structures or unions. These are the examples of anonymous union and structures. struct { datatype variable; ... }; union { datatype variable; ... };
A structure can be nested inside a union and it is called union of structures. It is possible to create a union inside a structure.
In C11 standard of C, anonymous Unions and structures were added. Anonymous unions/structures are also known as unnamed unions/structures as they don't have names. Since there is no names, direct objects(or variables) of them are not created and we use them in nested structure or unions.
according to http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields
-fms-extensions
will enable the feature you (and I) want.
(This answer applies to C99, not C11).
C99 does not have anonymous structures or unions. You have to name them:
typedef struct { union { struct { float x, y, z; } individual; float xyz[3]; } data; } Vector3;
And then you have to use the name when accessing them:
assert(&v.data.xyz[0] == &v.data.individual.x);
In this case, because your top level structure has a single item of type union, you could simplify this:
typedef union { struct { float x, y, z; } individual; float xyz[3]; } Vector3;
and accessing the data now becomes:
assert(&v.xyz[0] == &v.individual.x);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With