Skip to content

structures vs unions

Here’s a comparison between structures and unions presented in a tabular format:

FeatureStructuresUnions
DefinitionDefined using the struct keyword followed by member variables enclosed in braces {}.Defined using the union keyword followed by member variables enclosed in braces {}.
Memory AllocationEach member has its own memory space.All members share the same memory space.
SizeSize is equal to the sum of the sizes of its members.Size is equal to the size of its largest member.
Accessing MembersAccessed using the dot . operator.Accessed using the dot . operator or the arrow -> operator when working with pointers to unions.
Data IntegrityModifying one member does not affect other members.Modifying one member affects other members sharing the same memory space.
Use CasesUseful for grouping related data of different types.Useful for representing different interpretations of data in the same memory location.
Memory EfficiencyLess memory efficient if different members have different sizes.More memory efficient when representing different data types in the same memory location.
Examplec struct Point { int x; int y; };c union MyUnion { int i; float f; char c; };

This table summarizes the key differences between structures and unions, helping to understand when to use each based on specific programming requirements.