Search code examples
c++cstructunions

Anonymous union and a normal union


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.


Solution

  • 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.