I'm reading about anonymus structs and have problems understanding what is the privilege to have one. could anyone demonstrate an example of both anonymus and regular struct. I see that anonymus struct has a name after the the } and before semicolon. Any help would be greatly appreciated.

Thank you

7 Years
Discussion Span
Last Post by Ancient Dragon

take a look at this

Anonymous structures are not standard C therefore they are implemented as extensions. Anonymous structures are only useful as pointer targets, i.e.
"struct A *foo". You can pass around pointers to structures without
knowing the size of the structure, although you can't dereference them.

Anonymous unions are standard C and they are can be found inside an object or inside a namespace.

1. When an anonymous union is declared inside of an object the role is to have all data members of that class or struct to share the same memory space and they are accessed as any other datamembers. This is not considered a healthy practice and it can be used only with the system that do not have a good support for typecasting. reinterpret_cast is the recommended way over anonymous unions.

2. An anonymous union can be declared inside a namespace or at the global scope but because the unions members require internal linkage the union must be declared static.

Votes + Comments
C != C++, you should know that by now...

An anonymous struct can exist, but since you can't refer to it by a name, you need to instantiate it right away (unlike an anonymous union).


>>reinterpret_cast is the recommended way over anonymous unions.

reinterpret_cast is not allowed in C. So I don't know where you got your information but its wrong.

The only place I've used anonymous structs is inside a union

union something
          int x;
          int y;
    unsigned char buf[2 * sizeof(int)];

The most natural place for structures without tags is typedef declaration (it's the only place I've used anonymous structs ;)):

typedef struct 
} Record;
Record  rec;
Record* prec = &rec;

Of course, it's impossible to define self-referential structures in a such manner.

Yet another program case (less interesting):

struct { int x, y; } s;
struct { int x, y; } t;

Types of s and t are different. It's impossible to declare other variables of these types or to pass s and t as parameters.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.