Anonymous Union
It is well known in which a structure is a heterogeneous data type that permits to pack together variant categories of data values as a single unit. A union is also same to a structure data type with a difference in the way the data is stored and retrieved. The union stores values of various types in a single location. Union will holds one of several different categories of values. The general form of union is
union user_defined_name{
member1;
member 2;
member n;
};
the keyword union is used to declare the union data type. This is followed through a user_defined_name surrounded through braces that describes the member of the union.
Example:
union sample{
int x;
char s;
float t;
} one, two;
where one and two are the union variables same to data size of the sample.
It is possible to describe a union data type without a user_defined_name or tag and this type of declaration is known as an anonymous union.
The general form is
union{
member1;
member2;
---------;
member n;
};
The keyword union is used to declare the union data type. This is followed by braces that define the member of the union.
Eg.
union{
int x;
float a;
char ch;
};
Sample program:
#include <iostream.h>
void main(void)
{
union
{
int x;
float y;
cout<<"enter the information"<<endl;
cout<<"x(in integer)"<<endl;
cin>>x;
cout<<"y(in floating)"<<endl;
cin>>y;
cout<<"\n content of union"<<endl;
cout<<"x="<<x<<endl;
cout<<"y="<<y<<endl;
}
the output is
enter the information
x(in integer)
10
y(in floating)
34.90
content of union x=10
y=34.90