Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compile C code with anonymous structs / unions?

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 
like image 722
solinent Avatar asked Dec 28 '09 23:12

solinent


People also ask

How do you use an anonymous union?

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.

What is anonymous structure in C?

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; ... };

Can we declare union inside structure?

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.

Can we use structure without a name in a C program?

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.


2 Answers

according to http://gcc.gnu.org/onlinedocs/gcc/Unnamed-Fields.html#Unnamed-Fields

-fms-extensions will enable the feature you (and I) want.

like image 155
user287561 Avatar answered Sep 21 '22 04:09

user287561


(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); 
like image 36
R Samuel Klatchko Avatar answered Sep 19 '22 04:09

R Samuel Klatchko