Bird
Raised Fist0
C++programming~15 mins

Structure vs union comparison in C++ - Trade-offs & Expert Analysis

Choose your learning style10 modes available
Overview - Structure vs union comparison
What is it?
Structures and unions are ways to group different variables under one name in C++. 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, programmers would have to manage many separate variables, making code messy and error-prone. Structures let you keep related data together clearly, while unions save memory when only one value is needed at a time. This helps write efficient and organized programs, especially in systems with limited memory.
Where it fits
Before learning this, you should understand basic variables and data types in C++. After this, you can learn about classes and objects, which build on structures for more complex data organization.
Mental Model
Core Idea
Structures allocate separate memory for each member, while unions share the same memory space among all members.
Think of it like...
Think of a structure like a toolbox with separate compartments for each tool, so you can store all tools at once. A union is like a single drawer where you can only keep one tool at a time, but you save space by not having multiple compartments.
Structure:  ┌─────────┬─────────┬─────────┐
           │ Member1 │ Member2 │ Member3 │
           └─────────┴─────────┴─────────┘

Union:      ┌───────────────────────┐
           │ Shared Memory for All │
           └───────────────────────┘
Build-Up - 7 Steps
1
FoundationWhat is a structure in C++
🤔
Concept: Introduce the structure as a way to group variables with separate memory.
struct Point { int x; // stores x coordinate int y; // stores y coordinate }; Point p; p.x = 10; p.y = 20;
Result
You can access both x and y independently, and both keep their values separately.
Understanding that structures keep each member's data separately helps organize related information clearly.
2
FoundationWhat is a union in C++
🤔
Concept: Introduce the union as a way to group variables sharing the same memory space.
union Data { int i; // integer float f; // float }; Data d; d.i = 5; // Now d.f shares the same memory as d.i
Result
Only one member can hold a meaningful value at a time because they overlap in memory.
Knowing that unions save memory by overlapping members is key to using them correctly.
3
IntermediateMemory layout difference explained
🤔Before reading on: Do you think a structure and a union of the same members use the same amount of memory? Commit to your answer.
Concept: Explain how structures allocate memory for all members, unions allocate memory equal to the largest member.
struct Example { char c; // 1 byte int i; // 4 bytes }; union ExampleUnion { char c; // 1 byte int i; // 4 bytes }; // sizeof(Example) is usually 8 due to padding // sizeof(ExampleUnion) is 4, size of largest member
Result
Structures use more memory because they store all members separately; unions use less by sharing space.
Understanding memory layout helps optimize programs for size or speed.
4
IntermediateAccessing members and data safety
🤔Before reading on: If you write to one union member and read from another, do you get the original value or something else? Commit to your answer.
Concept: Show how accessing different union members can lead to unexpected results, unlike structures.
union U { int i; float f; }; U u; u.i = 42; float val = u.f; // reading different member struct S { int i; float f; }; S s; s.i = 42; float val2 = s.f; // independent members
Result
Union reading different member gives unpredictable data; structure members are independent.
Knowing this prevents bugs when using unions and ensures safe data access.
5
IntermediateUse cases for structures and unions
🤔
Concept: Explain when to use structures (grouping related data) and unions (memory optimization).
Structures are great for representing objects with multiple properties, like a 'Person' with name, age, and height. Unions are useful in low-level programming, like interpreting the same memory as different types or saving memory in embedded systems.
Result
Choosing the right type improves code clarity and efficiency.
Understanding use cases guides better design decisions in programming.
6
AdvancedPadding and alignment effects
🤔Before reading on: Do you think structures always use exactly the sum of their members' sizes? Commit to your answer.
Concept: Introduce how compilers add padding to structures for faster access, affecting size and layout.
struct Padded { char c; // 1 byte int i; // 4 bytes }; // Compiler adds 3 bytes padding after 'c' to align 'i' // sizeof(Padded) often 8 bytes, not 5 union U { char c; int i; }; // No padding in union, size is largest member size
Result
Structures may use more memory than expected due to padding; unions do not add padding between members.
Knowing padding helps understand memory usage and optimize data structures.
7
ExpertType punning and strict aliasing rules
🤔Before reading on: Is it safe to write to one union member and read from another to reinterpret data? Commit to your answer.
Concept: Explain how unions can be used for type punning but may violate strict aliasing rules, causing undefined behavior in some compilers.
union U { int i; float f; }; U u; u.i = 0x3f800000; // bit pattern for float 1.0 float val = u.f; // type punning // This works on many compilers but may break strict aliasing rules, // leading to optimization issues or undefined behavior. // Safer alternative: use memcpy to copy bytes between types.
Result
Using unions for type punning can be risky; understanding compiler rules is essential.
Knowing language rules prevents subtle bugs and undefined behavior in advanced code.
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, and all members share this address. Writing to one union member overwrites the shared memory, affecting all members.
Why designed this way?
Structures were designed to group related data with clear, independent storage for each part, making access straightforward. Unions were introduced to save memory when only one of several possible data types is needed at a time, useful in low-level programming and hardware interfacing.
Structures memory layout:
┌─────────┬─────────┬─────────┐
│ Member1 │ Member2 │ Member3 │
│ (addr1) │ (addr2) │ (addr3) │
└─────────┴─────────┴─────────┘

Unions memory layout:
┌─────────────────────────┐
│ Shared memory (largest)  │
│ (same address for all)   │
└─────────────────────────┘
Myth Busters - 4 Common Misconceptions
Quick: Does writing to one union member and reading from another always give the original value? Commit to yes or no.
Common Belief:You can safely write to one union member and read from another to convert data types.
Tap to reveal reality
Reality:This often causes undefined behavior due to strict aliasing rules in C++, making the result unpredictable.
Why it matters:Relying on this can cause bugs that are hard to find and may behave differently on various compilers.
Quick: Do structures and unions always use the same amount of memory if they have the same members? Commit to yes or no.
Common Belief:Structures and unions with the same members always use the same memory size.
Tap to reveal reality
Reality:Structures use memory equal to the sum of all members plus padding; unions use memory equal to the largest member only.
Why it matters:Misunderstanding this leads to inefficient memory use or buffer overflows.
Quick: Does a union allow storing multiple values at once like a structure? Commit to yes or no.
Common Belief:Unions can store multiple member values simultaneously like structures.
Tap to reveal reality
Reality:Unions can only store one member's value at a time because all members share the same memory.
Why it matters:Assuming unions hold multiple values causes data corruption and logic errors.
Quick: Is padding always added to unions like structures? Commit to yes or no.
Common Belief:Unions have padding between members just like structures.
Tap to reveal reality
Reality:Unions do not add padding between members because they overlap in memory; padding may only appear at the end for alignment.
Why it matters:Incorrect assumptions about padding can cause wrong size calculations and memory issues.
Expert Zone
1
Unions can be combined with structs to create tagged unions (variant types) for safer type management.
2
Compilers may optimize unions differently; understanding ABI (Application Binary Interface) details is crucial for cross-platform code.
3
Using anonymous unions inside structures allows overlaying memory without extra syntax, but can confuse code readability.
When NOT to use
Avoid unions when you need to store multiple values simultaneously or when strict type safety is required. Use structures or classes with variant types (like std::variant in C++) instead for safer and clearer code.
Production Patterns
Unions are commonly used in embedded systems to save memory and interpret hardware registers. Structures are used everywhere to model data objects. Tagged unions or variants combine both concepts for flexible and safe data handling in modern C++.
Connections
std::variant in C++
Builds-on
Understanding unions helps grasp how std::variant safely manages multiple types in one variable with type tracking.
Memory management in embedded systems
Same pattern
Knowing unions' memory sharing is essential for efficient resource use in devices with limited memory.
Human brain multitasking
Opposite pattern
Unlike unions that hold one value at a time, the brain can process multiple tasks simultaneously, highlighting different resource management strategies.
Common Pitfalls
#1Assuming union members hold independent values simultaneously.
Wrong approach:union U { int i; float f; } u; u.i = 10; u.f = 3.14; // expecting both values stored
Correct approach:union U { int i; float f; } u; u.i = 10; // only one member used at a time
Root cause:Misunderstanding that union members share the same memory location.
#2Reading a different union member than the one last written to, expecting meaningful data.
Wrong approach:union U { int i; float f; } u; u.i = 42; float val = u.f; // expecting val to be valid float
Correct approach:Use memcpy or std::bit_cast (C++20) to safely reinterpret data instead of direct union member access.
Root cause:Ignoring strict aliasing rules and undefined behavior in type punning.
#3Ignoring padding in structures leading to wrong size assumptions.
Wrong approach:struct S { char c; int i; }; // assuming sizeof(S) == 5 bytes
Correct approach:Check sizeof(S) which is usually 8 bytes due to padding for alignment.
Root cause:Not understanding compiler memory alignment and padding rules.
Key Takeaways
Structures allocate separate memory for each member, allowing all members to hold values simultaneously.
Unions share the same memory space among all members, so only one member can hold a valid value at a time.
Memory layout and padding affect the size and performance of structures and unions differently.
Using unions for type punning can cause undefined behavior; safer methods like memcpy or std::bit_cast are recommended.
Choosing between structures and unions depends on whether you need multiple values stored or memory optimization.

Practice

(1/5)
1. Which of the following best describes the main difference between a struct and a union in C++?
easy
A. A struct stores all members separately; a union shares memory among members.
B. A struct shares memory among members; a union stores all members separately.
C. Both struct and union store members separately but differ in syntax.
D. Both struct and union share memory but differ in member access.

Solution

  1. Step 1: Understand memory allocation in struct

    A struct allocates separate memory for each member, so all members can hold values simultaneously.
  2. Step 2: Understand memory allocation in union

    A union shares the same memory space for all members, so only one member can hold a valid value at a time.
  3. Final Answer:

    A struct stores all members separately; a union shares memory among members. -> Option A
  4. Quick Check:

    Struct = separate memory, Union = shared memory [OK]
Hint: Struct = all values stored; Union = one value stored [OK]
Common Mistakes:
  • Thinking union stores all members separately
  • Confusing struct and union memory sharing
  • Assuming both have same memory behavior
2. Which of the following is the correct syntax to define a union named Data with an int and a float member?
easy
A. struct Data { int i; float f; };
B. union Data ( int i; float f; );
C. union Data { int i; float f; };
D. union Data = { int i; float f; };

Solution

  1. Step 1: Recall union syntax

    The correct syntax uses the keyword union, followed by the name, and braces enclosing members separated by semicolons.
  2. Step 2: Check each option

    union Data { int i; float f; }; matches correct syntax. struct Data { int i; float f; }; uses struct, not union. union Data ( int i; float f; ); uses parentheses instead of braces. union Data = { int i; float f; }; uses an assignment which is invalid.
  3. Final Answer:

    union Data { int i; float f; }; -> Option C
  4. Quick Check:

    Union syntax = keyword + braces + members [OK]
Hint: Use braces {} with union keyword for definition [OK]
Common Mistakes:
  • Using struct keyword instead of union
  • Using parentheses instead of braces
  • Trying to assign values in definition
3. What will be the output of the following C++ code?
union Number {
  int i;
  float f;
};

int main() {
  Number n;
  n.i = 65;
  std::cout << n.f << std::endl;
  return 0;
}
medium
A. A floating-point number representing the bit pattern of 65
B. 0
C. 65
D. Compilation error

Solution

  1. Step 1: Understand union memory sharing

    Assigning 65 to n.i stores the integer bits in the shared memory.
  2. Step 2: Interpret bits as float

    Printing n.f reads the same bits as a float, resulting in a floating-point number representing the bit pattern of 65, not the integer 65.
  3. Final Answer:

    A floating-point number representing the bit pattern of 65 -> Option A
  4. Quick Check:

    Union shares bits; reading different type shows bit pattern [OK]
Hint: Union members share bits; reading different type shows bit pattern [OK]
Common Mistakes:
  • Expecting integer 65 to print as float 65.0
  • Assuming union stores separate copies
  • Thinking code causes compilation error
4. Identify the error in the following code snippet:
struct Data {
  int x;
  union {
    int i;
    float f;
  } u;
};

int main() {
  Data d;
  d.x = 10;
  d.u.i = 20;
  d.u.f = 3.14;
  std::cout << d.x << ", " << d.u.i << std::endl;
  return 0;
}
medium
A. Cannot assign float to union member.
B. Accessing union member after assigning another member leads to undefined value.
C. Missing semicolon after union definition.
D. Struct cannot contain a union as a member.

Solution

  1. Step 1: Analyze union member assignments

    Assigning d.u.i = 20; then d.u.f = 3.14; overwrites the same memory because union members share memory.
  2. Step 2: Understand reading union members

    Reading d.u.i after assigning d.u.f gives an undefined or unexpected value because only the last assigned member is valid.
  3. Final Answer:

    Accessing union member after assigning another member leads to undefined value. -> Option B
  4. Quick Check:

    Union stores one value; reading old member is invalid [OK]
Hint: Only last assigned union member holds valid data [OK]
Common Mistakes:
  • Thinking struct cannot have union member
  • Ignoring union memory sharing rules
  • Expecting both union members to hold values simultaneously
5. You want to store either an integer ID or a floating-point score in a variable but never both at the same time, and you want to save memory. Which is the best approach in C++?
hard
A. Use a class with private int and float members.
B. Use a struct with both int and float members.
C. Use two separate variables, one int and one float.
D. Use a union with int and float members.

Solution

  1. Step 1: Understand memory needs

    Since only one value (int or float) is needed at a time, memory can be saved by sharing storage.
  2. Step 2: Choose union for shared memory

    A union allows storing either int or float in the same memory space, saving memory compared to a struct which stores both separately.
  3. Step 3: Evaluate other options

    Using two separate variables wastes memory. A class with private members behaves like struct in memory. Struct stores both values simultaneously, using more memory.
  4. Final Answer:

    Use a union with int and float members. -> Option D
  5. Quick Check:

    Union saves memory when only one value needed [OK]
Hint: Use union to save memory when storing one of many types [OK]
Common Mistakes:
  • Choosing struct and wasting memory
  • Using separate variables unnecessarily
  • Confusing class with memory optimization
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard