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;
}
Leave a Reply