Anonymous unions are available in c++. anonymous unions are unions that do not have union tag. Besides this following restriction is applied on anonymous union.

  • when declaring globally they must be static.
  • Their elements must be public.
  • The declaration must not declare a variable of the union type.
  • Member function within them are not allowed.
  • A local anonymous union must be either static or automatic, not external.

The elements of anonymous union can be accessed directly without using union variable. Example code :

#include<iostream>
using namespace std;
static union       // Global anonymous
//unions must be static
{
   int i;
   union
   {
      char c;
   };
};

int main()
{
   i = 1;
   c = 'a';
return 0;
};

no static data members or member functions, no nonpublic members, and no nested types
(except anonymous classes, structures, or unions) are allowed in anonymous classes and anonymous structures. example code:

#include<iostream>
using namespace std;

#pragma anon_unions
struct A      
{
   struct{
   int i;
   };
};

int main()
{
   A a;
   a.i = 1;
return 0;
}

Note: if you want to use anonymous structure or class in c++ then you have to use #pragma anon_unions pragma.



Related Contents to follow