Union is a user-defined data type that is used to hold the different types of elements like structure. In union, all members share the same memory location.
Syntax:
1 2 3 4 5 6 7 8 9 |
union [union name] { member definition; member definition; ... member definition; }; |
Example
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 |
#include <stdio.h> union employe{ //defining a union int id; char name[32]; float salary; } uemp; struct structure_emp{ char name[32]; float salary; } sJob; int main() { printf("size of union = %d", sizeof(uemp)); printf("\nsize of structure = %d", sizeof(sJob)); return 0; } |
Output
1 2 3 4 |
size of union = 32 size of structure = 36 |
Difference between C structure and C union
C Structure | C Union |
It allocates storage space for all its members separately. | It allocates one common storage space for all its. |
It occupies height memory space. | It occupies lower memory space over the structure. |
All the member can be accessed at a time | Only one member can be accessed at a time |
Example:
struct employe { int id; char name[40]; float salary; }; |
Example:
union employe { int id; char name[40]; float salary; }; |