C – Unions
Structures in C language allow you to store data of different types, whereas Unions allow storing different datatype but in the same memory location.
Unions vs Structures
The Unions and Structures in C language are user-defined datatypes. Let us see the difference:
Definition
Structures in C allow you to store data of different types. The memory for each declared variable in a Structure is allocated to each variable member.
Unions in C allow you to store data of different types, but the memory for the declared variables in a Union is allocated to the largest memory.
Size
The size of the Structure is calculated by adding the sum of its members. Therefore, the size would be greater than or equal to the sum of each member’s size.
The size of the Union is not hard to calculate. It is the size of its largest member.
How to access members?
In Structures, the individual members can be accessed at a time.
In Union, you can access only one member at a time.
Keyword
To define a Structure, use the keyword struct.
To define a Union, use the keyword union.
Create a Union in C
Let us understand the Union concept with an example to define a union. To define a Union, use the union keyword:
0 comments:
Post a Comment