Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Anonymous union and a normal union

Tags:

c++

c

struct

unions

Can anybody please mention the differences between a normal and an anonymous union(or struct)? I have just found one:
functions can't be defined in anonymous union.

like image 670
akash Avatar asked Jun 15 '13 09:06

akash


People also ask

What is anonymous structure?

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. Definition is just like that of a normal union just without a name or tag.

What are unions in CPP?

In C++17 and later, the std::variant class is a type-safe alternative for a union. A union is a user-defined type in which all members share the same memory location. This definition means that at any given time, a union can contain no more than one object from its list of members.

Can a union only have one member?

You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

Can we have 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.


1 Answers

You don't require dot operator "." to access anonymous union elements.

#include <iostream> 
using namespace std;
int main() {
   union {
      int d;
      char *f;
   };

   d = 4;
   cout << d << endl;

   f = "inside of union";
   cout << f << endl;
}

This will successfully compile in this case but "NO" for normal Union.

Also, Anonymous union can only have public members.

PS :Simply omitting the class-name portion of the syntax does not make a union an anonymous union. For a union to qualify as an anonymous union, the declaration must not declare an object.

like image 73
S J Avatar answered Sep 24 '22 02:09

S J