Skip to main content

Comparion of Union vs Structures in C

Union vs Structures

Below is a detailed comparison table of the differences between union and structure in C:

UnionStructure
Memory allocation Allocates memory space for the largest member.Allocates memory space for each member.
Data storageCan hold only one member at a time.Can hold multiple members at a time.
Size of the data structureSize is equal to the largest member.Size is the sum of the sizes of all the members.
Accessing membersMembers can be accessed only one at a time.Members can be accessed individually or together.
Overwriting values Writing a value to one member will overwrite the values of other members.Writing a value to one member does not affect the values of other members.

Uses of Union

  • Storing multiple types of data in a single variable.
  • Reducing memory usage in certain cases.
  • Type punning (e.g., accessing the same memory as different types).
  • Implementing variant types or tagged unions.

Uses of Structure

  • Organizing related data.
  • Storing a collection of data of different types.
  • Defining complex data structures.
  • Implementing classes in C using function pointers.