In the world of C and C++ programming, Structures and Unions are fundamental user-defined data types. They allow programmers to group different types of variables under a single name, making code more readable and manageable. Although they share some similarities, structures and unions differ significantly in memory allocation, usage, and behavior. Understanding these differences is crucial for efficient programming and memory management.

This article explores the differences between structures and unions in detail, supported by syntax, examples, and use cases.

What is a Structure?

A structure (also known as struct) in C/C++ is a user-defined data type that allows grouping variables of different data types under one name. Each variable inside a structure is called a member of the structure.

Syntax:

struct StructureName {
dataType member1;
dataType member2;

};

Example:

#include <stdio.h>

struct Student {
int id;
char name[50];
float marks;
};

int main() {
struct Student s1 = {101, “Alice”, 92.5};

printf(“ID: %d\n”, s1.id);
printf(“Name: %s\n”, s1.name);
printf(“Marks: %.2f\n”, s1.marks);

return 0;
}

Explanation:
Each member of the structure has its own memory location, and all members can be accessed independently.

What is a Union?

A union in C/C++ is similar to a structure in that it can store different data types under a single name. However, all members of a union share the same memory location. This means only one member can hold a value at any time.

Syntax:

union UnionName {
dataType member1;
dataType member2;

};

Example:

#include <stdio.h>

union Data {
int intVal;
float floatVal;
char str[20];
};

int main() {
union Data d;

d.intVal = 10;
printf(“Int: %d\n”, d.intVal);

d.floatVal = 3.14;
printf(“Float: %.2f\n”, d.floatVal);

strcpy(d.str, “Hello”);
printf(“String: %s\n”, d.str);

return 0;
}

Explanation:
When you assign a value to one member, it overwrites the value of the previous member because all share the same memory.

Key Differences Between Structure and Union

Feature Structure Union
Memory Allocation Each member has its own memory space. All members share the same memory location.
Size Total size is the sum of all members’ sizes. Size is equal to the size of the largest member.
Access All members can be accessed independently. Only one member can be accessed at a time.
Use Case Suitable when all members are needed. Suitable when only one member is needed at a time.
Initialization All members can be initialized. Only the first member can be initialized.
Data Loss No data loss when accessing members. Data is overwritten when another member is accessed.
Syntax struct keyword is used. union keyword is used.
Memory Efficiency Less efficient than union in some cases. More memory-efficient when only one member is used.

Memory Allocation: A Deeper Look

Let’s take a closer look at how memory is managed in structures and unions.

Structure Memory Example:

struct Test {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};

Total memory = 4 + 4 + 1 = 9 bytes (may be more due to padding).

Union Memory Example:

union Test {
int a; // 4 bytes
float b; // 4 bytes
char c; // 1 byte
};

Total memory = 4 bytes (maximum of int, float, or char).

Observation:
In a structure, memory is allocated for each member. In a union, memory is allocated based on the size of the largest member, and all members share that space.

Real-Life Analogy

Structure:

Think of a structure as a multi-compartment bag. Each compartment (member) holds a different item (value), and all are available at once.

Union:

A union is like a single pocket in which you can store only one item at a time. If you put a new item in, the previous one is replaced.

When to Use Structures

Use structures when:

  • You need to store and access all fields simultaneously.
  • You want a record-like data type (e.g., storing data about a student).
  • The size of the structure doesn’t need to be minimal.

Example Use Case:

struct Employee {
int id;
char name[50];
float salary;
};

You can access id, name, and salary all at once.

When to Use Unions

Use unions when:

  • You only need one value at a time.
  • You want to save memory in embedded systems or constrained environments.
  • You’re working with variant data types, like in protocol headers or data packets.

Example Use Case:

union Value {
int intVal;
float floatVal;
char str[20];
};

void printValue(union Value v, int type) {
switch(type) {
case 0: printf(“Integer: %d\n”, v.intVal); break;
case 1: printf(“Float: %.2f\n”, v.floatVal); break;
case 2: printf(“String: %s\n”, v.str); break;
}
}

Nested Structures and Unions

You can nest structures inside unions or vice versa to create complex data structures.

Nested Structure in Union:

union Mixed {
int i;
struct {
char a;
float b;
} s;
};

Nested Union in Structure:

struct Mixed {
int id;
union {
int intData;
float floatData;
} data;
};

Common Pitfalls

  • Accessing the wrong member in a union can produce unexpected results.
  • Structures may consume more memory due to padding and individual allocation.
  • Unions cannot hold multiple values simultaneously — a common mistake among beginners.

Summary

Feature Structure Union
Keyword struct union
Memory Allocated separately for each member Shared among all members
Size Sum of all members’ sizes Size of the largest member
Access All members simultaneously One member at a time
Best Use Case Record-like data Memory-saving, variant data types

Final Thoughts

While both structures and unions are powerful tools for managing data in C and C++, choosing the right one depends on the requirements of your program. If your goal is to store multiple values at once, structures are your go-to. If memory efficiency is crucial and only one value is needed at a time, unions offer an optimal solution.

Mastering the difference between structures and unions not only enhances your understanding of memory management but also equips you to write cleaner and more efficient C programs.