Union in C
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:
union [union name] { member definition; member definition; ... member definition; };Example
#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
size of union = 32 size of structure = 36Difference 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; }; |