Here you gets all the basic differences between union and structure in the C programming language.
Structure | Union |
A structure is a user-defined data type available in C that allows to combining data items of different kinds. Structures are used to represent a record. | A union is a special data type available in C that allows storing different data types in the same memory location. |
All the members of the structure can be accessed at once. | Here a union only one member can be used at a time. |
The struct keyword is used to create a structure. | The union keyword is used to create a union. |
Several members of the structure can be initialized at once. | Only the first member of a union initialized. |
Altering the value of a member will not affect other members of the structure. | Altering the value of any member will alter the value of other members. |
For example: struct example { int integer; float floating_numbers; }; | For example: union example { int integer; float floating_numbers; }; |
The size allocated in the above example is sizeof(int) + sizeof(float); | The size allocated in the above example is the size of the highest member. So size is sizeof(float); |
It means the size occupied by the above structure will be 2+4=6 bytes. | It means the size occupied by an above union will be the size of float that is 4 bytes. |
The above are some of the basic difference between union and structure in C.