Bird
Raised Fist0
C++programming~10 mins

Union basics in C++ - Step-by-Step Execution

Choose your learning style10 modes available
Concept Flow - Union basics
Declare union variable
↓
Assign value to one member
↓
Access member value
↓
Note: all members share same memory
↓
Assign value to another member
↓
Access members again
↓
Observe that last assignment overwrites previous
A union lets you store different types in the same memory space, but only one at a time. Assigning to one member overwrites others.
Execution Sample
C++
union Data {
  int i;
  float f;
};

Data d;
d.i = 10;
float x = d.f;
This code declares a union with int and float, assigns 10 to int member, then reads float member.
Execution Table
StepActionMember Assigned/ReadValue StoredValue ReadNote
1Declare union variable d---Memory allocated for largest member (float or int)
2Assign d.i = 10i10 (int bits)-int member set, memory holds int bits for 10
3Read d.ii1010Reading int member returns 10
4Read d.ff10 (int bits)1.4e-44 (float)Reading float member interprets int bits as float
5Assign d.f = 5.5f5.5 (float bits)-float member set, overwrites memory
6Read d.ff5.55.5Reading float member returns 5.5
7Read d.ii5.5 (float bits)1085276160 (int)Reading int member interprets float bits as int
8End---Program ends
💡 Program ends after demonstrating union member assignments and reads
Variable Tracker
VariableStartAfter Step 2After Step 5Final
d.iundefined10bit pattern of 5.5 floatbit pattern of 5.5 float
d.fundefinedbit pattern of 10 int5.55.5
Key Moments - 3 Insights
Why does reading d.f after assigning d.i give a strange number?
Because d.i and d.f share the same memory, reading d.f interprets the int bits as a float (see execution_table step 4).
What happens when we assign d.f after assigning d.i?
The float assignment overwrites the shared memory, so the int value is lost (see execution_table step 5).
Can we store int and float values at the same time in a union?
No, only one member's value is valid at a time because all members share the same memory space.
Visual Quiz - 3 Questions
Test your understanding
Look at the execution_table, what value does d.f hold immediately after step 2?
A5.5 as a float
B10 as a float (1.4e-44)
C10 as an int
DUndefined
💡 Hint
Check step 4 in execution_table where d.f reads the bits of d.i = 10
At which step does the union memory get overwritten with a float value?
AStep 3
BStep 2
CStep 5
DStep 7
💡 Hint
Look at the Action column for assignment to d.f in execution_table
If we read d.i after step 5, what happens?
AWe get the int bits of 5.5 float interpreted as int
BWe get the int 10
CWe get 5.5 as int
DUndefined behavior
💡 Hint
See step 7 in execution_table for reading d.i after assigning d.f
Concept Snapshot
union Data {
  int i;
  float f;
};
- All members share the same memory.
- Assigning one member overwrites others.
- Reading a different member interprets the same bits differently.
Full Transcript
This visual trace shows how a union in C++ shares memory between its members. We declare a union with int and float members. Assigning to one member stores bits in shared memory. Reading another member interprets those bits differently. For example, assigning 10 to the int member and then reading the float member shows a strange float value because the bits represent an int 10, not a float 10. Assigning a float value overwrites the memory, so reading the int member then shows the int interpretation of the float bits. This demonstrates that only one member's value is valid at a time in a union.

Practice

(1/5)
1. What is the main characteristic of a union in C++?
easy
A. All members share the same memory location
B. Each member has its own separate memory
C. Unions can only store integers
D. Unions automatically initialize all members

Solution

  1. Step 1: Understand union memory sharing

    A union allocates one shared memory block for all its members, so they overlap.
  2. Step 2: Compare with other data structures

    Unlike structs, unions do not allocate separate memory for each member.
  3. Final Answer:

    All members share the same memory location -> Option A
  4. Quick Check:

    Union memory sharing = All members share the same memory location [OK]
Hint: Remember: union members overlap in memory [OK]
Common Mistakes:
  • Thinking each member has separate memory
  • Assuming unions initialize all members
  • Believing unions only store one data type
2. Which of the following is the correct syntax to define a union named Data with an int and a float member?
easy
A. union Data = { int i; float f; };
B. struct 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 declaration syntax

    Unions are declared using the keyword union, followed by the name and braces with members inside.
  2. Step 2: Check each option

    union Data { int i; float f; }; uses correct syntax with braces and semicolons. Options B, C, and D have syntax errors or wrong keywords.
  3. Final Answer:

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

    Correct union syntax = union Data { int i; float f; }; [OK]
Hint: Use 'union Name { members; };' syntax [OK]
Common Mistakes:
  • Using struct keyword instead of union
  • Using parentheses instead of braces
  • Assigning values in declaration
3. What will be the output of the following code?
union Number {
  int i;
  float f;
};

Number n;
n.i = 65;
std::cout << n.f << std::endl;
medium
A. A floating-point number representing the bits of 65
B. 65.0
C. 0
D. Compilation error

Solution

  1. Step 1: Understand union memory sharing and type punning

    Assigning to n.i sets the bits of the union. Reading n.f interprets those bits as a float.
  2. Step 2: Predict output

    The bits for integer 65 do not represent 65.0 as a float, so output is a float number corresponding to those bits, not 65.0.
  3. Final Answer:

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

    Union type punning = A floating-point number representing the bits of 65 [OK]
Hint: Union shares bits; int bits read as float show strange value [OK]
Common Mistakes:
  • Expecting output 65.0
  • Assuming union members hold independent values
  • Thinking code causes compile error
4. Identify the error in this union usage:
union Data {
  int i;
  char c;
};

Data d;
d.i = 100;
d.c = 'A';
std::cout << d.i << std::endl;
medium
A. Output will be 100
B. Error: Cannot assign to union members separately
C. No error; output will be 65
D. Compilation error due to missing semicolon

Solution

  1. Step 1: Understand union member assignment

    Assigning to d.i then to d.c overwrites the same memory because union members share memory.
  2. Step 2: Determine final value of d.i

    After d.c = 'A', the first byte of d.i is set to ASCII 65, so printing d.i shows 65.
  3. Final Answer:

    No error; output will be 65 -> Option C
  4. Quick Check:

    Union last write wins = No error; output will be 65 [OK]
Hint: Last assigned union member overwrites memory [OK]
Common Mistakes:
  • Thinking union members hold values independently
  • Expecting output 100 after assigning 'A'
  • Assuming syntax error
5. You want to store either an int, a float, or a char in the same memory space efficiently. Which union definition and usage correctly allows this, and how do you safely read the stored value?
hard
A. union Value { int i; float f; char c; }; Value v; v.i = 10; std::cout << v.c << std::endl;
B. union Value { int i; float f; char c; }; Value v; v.f = 3.14f; std::cout << v.f << std::endl;
C. union Value { int i; float f; char c; }; Value v; v.c = 'Z'; std::cout << v.i << std::endl;
D. union Value { int i; float f; char c; }; Value v; std::cout << v.i << std::endl;

Solution

  1. Step 1: Check union definition and assignment

    union Value { int i; float f; char c; }; Value v; v.f = 3.14f; std::cout << v.f << std::endl; defines a union with int, float, char and assigns a float value correctly.
  2. Step 2: Verify safe reading of stored value

    union Value { int i; float f; char c; }; Value v; v.f = 3.14f; std::cout << v.f << std::endl; reads the same member v.f that was assigned, ensuring correct interpretation.
  3. Step 3: Analyze other options

    Other options either assign to one member and read a different one, leading to unexpected values, or read uninitialized memory.
  4. Final Answer:

    union Value { int i; float f; char c; }; Value v; v.f = 3.14f; std::cout << v.f << std::endl; -> Option B
  5. Quick Check:

    Read the same union member you wrote [OK]
Hint: Always read the union member you last wrote [OK]
Common Mistakes:
  • Reading a different member than assigned
  • Using uninitialized union members
  • Assuming union members hold independent values
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