0
0
Cprogramming~15 mins

Structure vs union comparison - Trade-offs & Expert Analysis

Choose your learning style9 modes available
Overview - Structure vs union comparison
What is it?
Structures and unions are ways to group different variables under one name in C programming. A structure stores each member separately, so all members have their own space. A union shares the same memory space for all members, so only one member can hold a value at a time. Both help organize related data but work differently in memory.
Why it matters
Without structures and unions, managing related data would be messy and error-prone, requiring separate variables for each piece. Structures let you keep multiple related values together safely, while unions save memory when you only need one value at a time. This makes programs easier to write, read, and more efficient.
Where it fits
Before learning structures and unions, you should understand basic variables and data types in C. After this, you can learn about pointers, dynamic memory, and advanced data structures like linked lists that use structures heavily.
Mental Model
Core Idea
Structures store all members separately in memory, while unions share the same memory space for all members, allowing only one active value at a time.
Think of it like...
Think of a structure like a toolbox with separate compartments for each tool, so you can keep all tools at once. A union is like a single drawer where you can only keep one tool at a time, but the drawer size fits the biggest tool.
Structure vs Union Memory Layout:

Structure:          Union:
+-------+          +-------+
| int   |          |       |
+-------+          |       |
| float |          |       |
+-------+          |       |
| char  |          |       |
+-------+          +-------+

Structure members have separate boxes stacked vertically.
Union members share the same box.
Build-Up - 7 Steps
1
FoundationUnderstanding basic structures
🤔
Concept: Introduce how structures group multiple variables with separate memory.
In C, a structure groups variables under one name. Each member has its own memory space. Example: struct Point { int x; int y; }; struct Point p; p.x = 10; p.y = 20; Here, x and y are stored separately inside p.
Result
You can store and access multiple related values together, each keeping its own data.
Knowing that structures allocate separate memory for each member helps understand how data is stored and accessed.
2
FoundationIntroducing unions and shared memory
🤔
Concept: Explain unions as a way to share memory among members.
A union groups variables but all members share the same memory space. Example: union Data { int i; float f; char c; }; union Data d; d.i = 5; // Now d.f and d.c share the same memory as d.i Only one member can hold a meaningful value at a time.
Result
Memory size equals the largest member, saving space but limiting simultaneous values.
Understanding shared memory in unions reveals how they save space but require careful use.
3
IntermediateMemory size differences explained
🤔Before reading on: Do you think a union always uses less memory than a structure? Commit to your answer.
Concept: Compare how memory size is calculated for structures and unions.
Structure size is the sum of all members' sizes plus padding. Union size is the size of its largest member. Example: struct S { char c; int i; } size might be 8 bytes (due to padding). union U { char c; int i; } size is 4 bytes (largest member int). Padding aligns data for faster access.
Result
Structures usually use more memory than unions with the same members.
Knowing how memory size differs helps choose between structures and unions based on space needs.
4
IntermediateAccessing members and data safety
🤔Before reading on: Can you safely read all members of a union at any time? Commit to your answer.
Concept: Explain how accessing union members works and risks of reading inactive members.
In structures, all members hold valid data simultaneously. In unions, only the last assigned member holds valid data. Reading a different member than the last written can cause unexpected results. Example: union U { int i; float f; } u; u.i = 10; float x = u.f; // May give garbage value Programmers must track which member is active.
Result
Incorrect member access in unions can cause bugs or wrong data.
Understanding member validity in unions prevents subtle bugs in programs.
5
IntermediateUse cases for structures and unions
🤔
Concept: Show when to use structures vs unions in real programs.
Use structures when you need to store multiple related values at once. Use unions when you want to save memory and only one value is needed at a time. Example: Structure: storing a 2D point with x and y. Union: storing a variable that can be int or float but never both simultaneously. Sometimes unions are combined with an enum to track active member.
Result
Choosing the right type improves program clarity and efficiency.
Knowing practical use cases guides better design decisions in coding.
6
AdvancedCombining unions with structs for tagged unions
🤔Before reading on: Do you think a union alone can safely store multiple types without extra info? Commit to your answer.
Concept: Introduce tagged unions by combining a union with a type indicator.
A tagged union uses a struct with a union and a tag (usually an enum) to track active member. Example: struct Value { enum { INT, FLOAT } type; union { int i; float f; } data; }; This lets programs know which union member is valid. Tagged unions are safer and common in complex programs.
Result
You can safely store and check multiple types in one variable.
Understanding tagged unions reveals how to use unions safely in real-world code.
7
ExpertMemory alignment and padding surprises
🤔Before reading on: Does union always have no padding between members? Commit to your answer.
Concept: Explore how alignment rules affect structures and unions differently, causing unexpected sizes.
Structures may have padding between members to align data. Unions align to the strictest member's alignment. Sometimes unions have padding at the end to satisfy alignment in arrays. Example: union U { char c; double d; }; Size is aligned to double's alignment, possibly adding padding. This affects memory layout and performance.
Result
Knowing alignment helps optimize memory and avoid bugs in low-level code.
Understanding alignment and padding nuances prevents subtle memory and performance issues.
Under the Hood
Structures allocate memory for each member sequentially, with possible padding for alignment. Each member has its own address. Unions allocate a single memory block sized to the largest member. All members share this block, overlapping in memory. The compiler manages alignment and padding to ensure efficient access and hardware compatibility.
Why designed this way?
Structures were designed to group related data with independent storage for clarity and ease of use. Unions were introduced to save memory when only one of several types is needed at a time, useful in low-memory systems or hardware interfacing. The design balances programmer convenience and system efficiency.
Memory Layout:

Structures:
+-------+-------+-------+
| Member1 | Member2 | Member3 |
+-------+-------+-------+

Unions:
+-----------------------+
| Shared Memory (largest member size) |
+-----------------------+

Access:
Structures: each member at different address
Unions: all members at same address
Myth Busters - 4 Common Misconceptions
Quick: Does a union store all its members' values at the same time? Commit yes or no.
Common Belief:A union stores all its members' values simultaneously like a structure.
Tap to reveal reality
Reality:A union only stores one member's value at a time because all members share the same memory space.
Why it matters:Assuming all union members hold valid data leads to reading garbage values and bugs.
Quick: Is the size of a union always the sum of its members' sizes? Commit yes or no.
Common Belief:The size of a union is the sum of all its members' sizes.
Tap to reveal reality
Reality:The size of a union is equal to the size of its largest member, not the sum.
Why it matters:Misunderstanding size causes wrong memory allocation and potential crashes.
Quick: Can you safely read any member of a union regardless of what was last written? Commit yes or no.
Common Belief:You can read any union member at any time safely.
Tap to reveal reality
Reality:Only the last written member holds valid data; reading others can cause incorrect results.
Why it matters:Ignoring this causes subtle bugs and unpredictable program behavior.
Quick: Does padding only affect structures, not unions? Commit yes or no.
Common Belief:Padding only applies to structures, unions have no padding.
Tap to reveal reality
Reality:Unions also have padding to align to the strictest member's alignment requirements.
Why it matters:Ignoring union padding can cause unexpected memory sizes and alignment bugs.
Expert Zone
1
Unions combined with enums (tagged unions) are a foundation for variant types in many languages, enabling safe polymorphism.
2
Compilers may reorder structure members for better packing unless explicitly prevented, affecting memory layout assumptions.
3
Using unions for type punning (interpreting the same memory as different types) can lead to undefined behavior unless carefully controlled.
When NOT to use
Avoid unions when you need to store multiple values simultaneously; structures are better. For complex variant data, consider higher-level abstractions like tagged unions or polymorphic types in other languages. Also, avoid unions for type punning in strict aliasing contexts; use memcpy or standard conversions instead.
Production Patterns
Tagged unions are widely used in parsers, interpreters, and protocol implementations to represent variant data safely. Structures are the default for grouping related data like records or objects. Unions optimize memory in embedded systems or hardware drivers where memory is limited and only one data type is active at a time.
Connections
Tagged unions in functional programming
Builds-on
Understanding C unions with tags helps grasp algebraic data types in functional languages, which safely represent variant data.
Memory management in embedded systems
Same pattern
Using unions to save memory is a common pattern in embedded programming where resources are limited.
Human multitasking and focus
Analogy to mental resource sharing
Just like a union shares memory for one active value, humans can focus on one task at a time to use mental resources efficiently.
Common Pitfalls
#1Reading a union member different from the last written one.
Wrong approach:union U { int i; float f; } u; u.i = 42; float x = u.f; // Incorrect: reading inactive member
Correct approach:union U { int i; float f; } u; u.f = 3.14f; float x = u.f; // Correct: reading active member
Root cause:Misunderstanding that union members share memory and only one holds valid data.
#2Assuming union size is sum of members' sizes.
Wrong approach:union U { char c; int i; } u; printf("Size: %zu", sizeof(u)); // Assumes size is sizeof(char)+sizeof(int)
Correct approach:union U { char c; int i; } u; printf("Size: %zu", sizeof(u)); // Size equals largest member, usually sizeof(int)
Root cause:Confusing union memory layout with structure layout.
#3Ignoring padding and alignment in structures causing unexpected size.
Wrong approach:struct S { char c; int i; } s; printf("Size: %zu", sizeof(s)); // Assumes size is 5 bytes
Correct approach:struct S { char c; int i; } s; printf("Size: %zu", sizeof(s)); // Actual size includes padding, often 8 bytes
Root cause:Not accounting for compiler-inserted padding for alignment.
Key Takeaways
Structures allocate separate memory for each member, allowing simultaneous storage of all members.
Unions share the same memory space for all members, so only one member can hold a valid value at a time.
The size of a union equals its largest member's size, while a structure's size is roughly the sum of its members plus padding.
Accessing inactive union members leads to undefined or unexpected values, so tracking the active member is essential.
Combining unions with tags (enums) creates safe variant types, widely used in real-world programming.