Anonymous unions

Anonymous unions are the unions that do not have any union< tag> or union name but we can access its elements directly without using a union variable  

In C we can not access union elements without a union variable 

#include <stdio.h>
int main()
{
    union abc{
int a;
char b;
};
    a=50; //error a is undeclared and b is undeclared
    printf("a=%d\n", a);
    printf("b=%c\n", b);
    return 0;
}

But, in C++ we can access union elements without a union variable and union <tag>or union name

Similarly, if you use the keyword struct instead of the keyword union then, in that case, you will see an error[abstract declaratory ‘main()::<anonymous struct>’ used as declaration]

#include <iostream>
using namespace std;
int main()
{
    union {
int a;
char b;
};
    a=50;
    cout << "a=" <<a<< endl;
    cout << "b=" <<b<< endl;
    return 0;
}

Output

a=50
b=2

In C++ if we declare the anonymous union outside the main() function then, in that case, we can not access its elements without a variable name

#include <iostream>
using namespace std;
   union {
int a;
char b;
};
int main()
{
    a=50; //error: a was not declared in this scope
    cout << "a=" <<a<< endl;
    cout << "b=" <<b<< endl;//Error: b was not declared in this scope
    return 0;
}

Mohammed Anees

Hey there, welcome to aneescraftsmanship I am Mohammed Anees an independent developer/blogger. I like to share and discuss the craft with others plus the things which I have learned because I believe that through discussion and sharing a new world opens up

Leave a Reply

Your email address will not be published.