- Like structure union is also a collection of similar and dissimilar data types but difference is that it holds only one object at a time.
- As we know in structure every data member has its own memory location but data members of unions have same memory address.
- Union can contain one member at a time in a single area of storage.
- Union can contain the members of different-different data type like int, float, char etc.
- The size of union is equal to the size of the largest data member present in union.
- Union takes less memory because it occupies the memory of largest member of union.
- The basic syntax to declare a union is as follows:
- We can access the union member with the help of '.' (Dot operator) like structure.
- Here is an example of Union:
} [one or more union variables];
union data d;
printf("Size of union:%d",sizeof(d));
The output of the above program is as follows:
data1=300123, data2= 323031, data3=H
In the above example union contains three variables int, float and char. As we know int , float and char occupies 4,4 and 1 byte respectively in the memory location that is why union contains size of largest data member that is 4. Here, we can see that values of data1 and data2 members of union are garbage values because final value assigned to the variable has occupied the memory location and this is the reason that the value of data member data 3 is getting printed very well.