Difference Between Structure and Union

Learn via video courses
Topics Covered

Overview

Structures and Unions are user-defined data types to store multiple data types used in real-life applications. These make our codes readable which in turn makes debugging easier. The key difference between structure and union lies in their memory allocation. While structures allocate individual memory space for each member, unions share the same memory space for all members, resulting in a size determined by the largest member.

In real-world applications, the primitive data types fall short in fulfilling our needs. Since they are not able to store multiple data types for us, we have to use multiple variables for different data types.

This makes our program difficult to understand and read. Also, it makes debugging a lot harder, and we might need to make numerous changes in our program.

To solve this issue, we need a data type that can model real-world entities and offer us a more structured and readable code. All these in turn, would make debugging a lot easier.

What is a Structure?

what is structure A structure is a user-defined data type provided to us in C and C++. It is a data type that is used to create custom types according to users’ needs. It is a collection of more than one variable of different data types, which are all allocated specific memory.

What is a Union?

what is union A union is also one of the user-defined data types provided to us in C and C++. Like structure, a union can store more than one variable of different data types. But in a union, every data member declared is not individually allocated memory.

Here we skimp on using extra memory, and we allocate memory of the largest size data variable as the memory of the union. Whenever we update a data member, all other data members get updated with the same new value if they are of the same data type or a garbage value is assigned to them.

This does not allow us to update and access all data members simultaneously but saves us memory.

Difference Between Structure and Union: Key Differences

The key difference between structure and union are shown below.

StructureUnion
DefineKeyword ‘struct’ is used to define a structureKeyword ‘union’ is used to define a union
SizeThe size of a structure is the sum of the size of all data members and the packing size.The size of the union is the size of its data member, which is the largest in size.
Memory managementInefficient and requires packing memoryEfficient
Data membersAll data members store some value at every point in the programOnly the latest initialized data member stores the value.
Memory allocationAll the data members are provided appropriate memory at different memory addressesAll data members share a single memory address and occupy the memory of the largest data member
Initialisation of data membersAll the data members could be initialised at onceOnly one data member can be initialized at a time.
UpdationUpdation of every data member is independent of the value stored in other data membersUpdation of any data member leads to changes in values stored in other data members.
Data members valueWe can access data members' exact values if they are initialized.Only the latest initialized data member returns its exact value. All other data members return garbage values.
Accessing data members‘.’ operator is used to access the data members‘.’ operator is used to access the data members
Memory UsageGenerally more memory is used due to separate memory allocation.Saves memory by sharing space among members.
Use CasesPreferred for complex data structures with various members.Suitable for scenarios where memory efficiency is crucial.

Syntax of Declaring Structure

Structures are declared using the ‘struct’ keyword followed by the structure name. The data members of the structure are declared within the curly ‘{}’ brackets. The structure is completed by ‘;’ after its declaration.

Defining a structure

Declaration and Assignment

Initialisation

Since separate memory is allocated to all the data members of the structure, we can update any data member without affecting the other data members. This allows the user to store and access different variables of a structure simultaneously.

Size

Every data member that is declared in the structure is individually allocated specific memory according to its data type.

For example, a structure with data members is as follows.

  • Int – 4 bytes
  • Char – 2 bytes
  • Float – 8 bytes The total size of the structure

sizeof(int) + sizeof(char) + sizeof(float) + packing size

sizeof() is a keyword that returns the amount of memory allocated to the object passed to it. The size is returned to us in bytes.

The packing size is the memory used by the compiler to put all the structure members of a structure into the memory.

Accessing the data members

The data members of the structure are accessed using the ‘.’ operator.

This shows that a structure can help us define a data type that contains numerous attributes of a single entity of different data types. We also see that structure provides us an encapsulated view of the entity it models. This improves the readability of our code a lot.

Structure Code:

Syntax of Declaring Union

Unions are declared using the ‘union’ keyword followed by the union name. The data members of the union are declared within the curly ‘{}’ brackets. The union is completed ‘;’ after its declaration.

Defining a union

Declaration and Assignment

Initialisation

In a union we can only initialize the first data member of the union. Even giving multiple values to the union cannot help to initialize multiple members. Not more than one member can be initialized here because we are always sharing the memory.

If we want to initialize some other data member instead of the first member, then we have to use a designated initializer with the help of ‘.’ access operator.

For example:

This shows that a union can also serve many functions of a structure with efficient memory usage.

Union Code:

Structure Advantage

  • Value structures allow us to store multiple data values associated with any entity together.
  • Structures enable us to initialize any number of data members.
  • Separate memory is allocated to all data members, and they can be updated without changing other data member's values
  • We can pass either structure with multiple data members or individual data members easily to functions
  • We can implement flexible size arrays in structures

Structure Disadvantages

  • They are memory inefficient since they need the packing memory for creating every structure.
  • They are slower to implement.

Union Advantages

  • Unions allow us to store multiple data values associated with any entity together.
  • Single memory space is shared by members, and they cannot be structured out of changing other data members values

Union Disadvantages

  • We can access only one data member at a time. We can get the value of only the latest initialized data member.
  • We can initialize only one data member.
  • We cannot implement flexible size arrays in unions.
  • Its members can be passed to functions, but their values will be affected whenever any other data member is updated.

Conclusion

  • Structures and unions are user-defined data types used in real-life applications, enhancing code readability and facilitating debugging.
  • The key difference between structure and union in C lies in memory allocation. Structures allocate separate memory for each member, while unions share memory, resulting in a size determined by the largest member.
  • Structures provide advantages like storing multiple data values, easy initialization, and passing to functions, but they can be memory inefficient and slower to implement.
  • Unions save memory by sharing space, but they can access only one member at a time, have limited initialization, and lack flexible size arrays.