Differences Between Structures and Unions in C Programming
In C programming, both structures and unions are user-defined data types that allow you to store multiple variables of different types under a single name. While they share some similarities, the way they handle memory and data is quite different. Understanding these differences is crucial for deciding which one to use depending on your programming needs.
At SamagraCS Educational Technology, we will take you step-by-step through the differences between structures and unions to help you make informed choices in your C programming journey.
What Are Structures and Unions?
- A structure in C allows you to group multiple related variables (of different types) together, with each member having its own memory space.
- A union in C allows you to group multiple related variables, but they all share the same memory location, meaning only one member can hold a value at a time.
Detailed Differences Between Structures and Unions
Below is a comprehensive comparison between structures and unions, presented in an easy-to-understand tabular format.
Feature | Structure | Union |
---|---|---|
Memory Allocation | Each member has its own memory location. | All members share the same memory location. |
Size | The total size of a structure is the sum of the sizes of all its members. | The size of a union is equal to the size of its largest member. |
Access to Members | All members can be accessed simultaneously. | Only one member can hold a value at a time. Assigning a value to one member will overwrite the previous value. |
Usage Scenario | Used when you need to store multiple values at the same time, each in its own memory space. | Used when you need to store different types of data, but only one value at a time to save memory. |
Member Value Changes | Changing one member’s value does not affect other members. | Changing one member’s value overwrites the value of other members because they share memory. |
Memory Efficiency | Less memory-efficient because each member gets its own memory allocation. | More memory-efficient as all members share the same memory. |
Size Example | If a structure has an int (4 bytes), float (4 bytes), and char[20] (20 bytes), the size will be 28 bytes. | If a union has the same members, the size will be 20 bytes (size of the largest member, char[20] ). |
Initialization | You can initialize multiple members of a structure at the same time. | You can only initialize one member of a union at a time. |
Real-Life Analogy | Like a house with multiple rooms, where each room has its own space. | Like a shared locker, where only one item can be stored at a time. |
Example Code | struct { int i; float f; char str[20]; } | union { int i; float f; char str[20]; } |
Memory Allocation in Structures and Unions
Structure:
Each member of a structure occupies its own memory, so the total size of a structure is the sum of the memory size required by each member.
Union:
In a union, all members share the same memory location, so the memory allocated for the union is equal to the size of its largest member.
Example:
Here’s how memory allocation differs between a structure and a union:
#include <stdio.h>
struct StructExample {
int i;
float f;
char str[20];
};
union UnionExample {
int i;
float f;
char str[20];
};
int main() {
printf("Size of structure: %lu bytes\n", sizeof(struct StructExample)); // Output: 28 bytes
printf("Size of union: %lu bytes\n", sizeof(union UnionExample)); // Output: 20 bytes
return 0;
}
Output:
Size of structure: 28 bytes
Size of union: 20 bytes
- Structure Size: The structure’s size is 28 bytes, which is the total size of
int
(4 bytes),float
(4 bytes), andchar[20]
(20 bytes). - Union Size: The union’s size is 20 bytes, which is the size of its largest member,
char[20]
.
Example: Practical Usage of Structures and Unions
Using a Structure:
Let’s say we need to store information about a student, such as their ID, name, and marks. Since we need to store multiple values, we use a structure.
#include <stdio.h>
struct Student {
int id;
char name[50];
float marks;
};
int main() {
struct Student student1 = {1, "Pawan Jaiswal", 85.5};
// Access and print structure members
printf("ID: %d\n", student1.id);
printf("Name: %s\n", student1.name);
printf("Marks: %.2f\n", student1.marks);
return 0;
}
Output:
ID: 1
Name: Pawan Jaiswal
Marks: 85.50
Here, we store multiple values (ID, name, and marks) at the same time, which is why a structure is ideal.
Using a Union:
Now, let’s say we need to store information about an employee who may have either an ID, a salary, or a department name at any given time, but not all three simultaneously. In this case, a union is more memory-efficient.
#include <stdio.h>
#include <string.h>
union Employee {
int id;
float salary;
char department[20];
};
int main() {
union Employee emp;
// Store and print employee ID
emp.id = 101;
printf("Employee ID: %d\n", emp.id);
// Store and print employee salary
emp.salary = 55000.75;
printf("Employee Salary: %.2f\n", emp.salary);
// Store and print employee department
strcpy(emp.department, "HR");
printf("Employee Department: %s\n", emp.department);
return 0;
}
Output:
Employee ID: 101
Employee Salary: 55000.75
Employee Department: HR
In this example, notice how we only store one value at a time in the union. Assigning a new value to the union overwrites the previous one.
When to Use Structures and Unions
Use Structures When:
- You need to store multiple values simultaneously.
- Each member must retain its own value, independent of the others.
- You don’t need to optimize memory usage as much.
Use Unions When:
- You only need to store one value at a time.
- Memory efficiency is crucial.
- You are working in a low-memory environment like embedded systems.
Real-Life Analogies
- Structure: Think of a structure like a house with multiple rooms, where each room serves a different purpose (bedroom, kitchen, etc.), and all the rooms exist at the same time.
- Union: Think of a union like a shared locker, where you can only store one item at a time. Storing a new item removes the previous one.
Both structures and unions are essential tools in C programming, but they serve different purposes:
- Structures are used when you need to store multiple values at the same time, each with its own memory space.
- Unions are used when you want to save memory and store only one value at a time, even though the data type may change.
At SamagraCS Educational Technology, we encourage students to practice using both structures and unions in different scenarios to get a better understanding of when and how to use each. With practice, you’ll be able to choose the right data type for every situation.
For any questions or assistance, feel free to reach out to Pawan & Pooja, or the team at SamagraCS Educational Technology. Happy coding!