Unions are user-defined data type in C, Union is a data type in C programming that allows different data types to be stored in the same memory locations.
You can define a union with many members, but only one member can contain a value at any given time.
We can access only one member of union at a time. We can’t access all member values at the same time in union
Unions are conceptually similar to Structures. The only difference between them is memory allocation. Structure allocates storage space for all its members separately; Whereas, Union allocates one common storage space for all its members.
union tagname { datatype member1; datatype member2; ....... ....... };
About union
union Employee{ int age; long salary; } employee={20000};
Memory size occupied by data : 20
Union members can be accessed the same way as structure members are accessed. To access any member of a union, we use the member access operator (.).
data.i : 1917853763 data.f : 4122360580327794900000000000000.000000 data.str : C Programming
Structure | Union | |
---|---|---|
1 | For defining structure use struct keyword. | For defining union we use union keyword |
2 | Structure occupies more memory space than union. | Union occupies less memory space than Structure. |
3 | In Structure we can access all members of structure at a time. | In union we can access only one member of union at a time. |
4 | Structure allocates separate storage space for its every members. | Union allocates one common storage space for its all members. Union find which member need more memory than other member, then it allocate that much space |