Union basics in C++ - Time & Space Complexity
When working with unions in C++, it's helpful to understand how operations on them scale as data changes.
We want to see how the time to access or modify union members grows with input size.
Analyze the time complexity of the following code snippet.
union Data {
int i;
float f;
char str[20];
};
void setInt(Data &d, int value) {
d.i = value;
}
int getInt(const Data &d) {
return d.i;
}
This code defines a union with different types and functions to set and get an integer value.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Direct assignment and access of union members.
- How many times: Each operation happens once per function call, no loops or recursion.
Accessing or setting a union member takes the same time regardless of input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | 1 |
| 100 | 1 |
| 1000 | 1 |
Pattern observation: The time stays constant no matter how big the input is.
Time Complexity: O(1)
This means accessing or setting a union member takes the same amount of time no matter what.
[X] Wrong: "Accessing different union members takes longer as the union grows."
[OK] Correct: A union shares memory for all members, so accessing any member is a simple direct operation that does not depend on union size.
Understanding that unions provide constant-time access helps you explain memory-efficient data handling clearly and confidently.
What if we added a loop to copy each character of the union's string member? How would the time complexity change?
Practice
union in C++?Solution
Step 1: Understand union memory sharing
A union allocates one shared memory block for all its members, so they overlap.Step 2: Compare with other data structures
Unlike structs, unions do not allocate separate memory for each member.Final Answer:
All members share the same memory location -> Option AQuick Check:
Union memory sharing = All members share the same memory location [OK]
- Thinking each member has separate memory
- Assuming unions initialize all members
- Believing unions only store one data type
Data with an int and a float member?Solution
Step 1: Recall union declaration syntax
Unions are declared using the keywordunion, followed by the name and braces with members inside.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.Final Answer:
union Data { int i; float f; }; -> Option DQuick Check:
Correct union syntax = union Data { int i; float f; }; [OK]
- Using struct keyword instead of union
- Using parentheses instead of braces
- Assigning values in declaration
union Number {
int i;
float f;
};
Number n;
n.i = 65;
std::cout << n.f << std::endl;Solution
Step 1: Understand union memory sharing and type punning
Assigning ton.isets the bits of the union. Readingn.finterprets those bits as a float.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.Final Answer:
A floating-point number representing the bits of 65 -> Option AQuick Check:
Union type punning = A floating-point number representing the bits of 65 [OK]
- Expecting output 65.0
- Assuming union members hold independent values
- Thinking code causes compile error
union Data {
int i;
char c;
};
Data d;
d.i = 100;
d.c = 'A';
std::cout << d.i << std::endl;Solution
Step 1: Understand union member assignment
Assigning tod.ithen tod.coverwrites the same memory because union members share memory.Step 2: Determine final value of
Afterd.id.c = 'A', the first byte ofd.iis set to ASCII 65, so printingd.ishows 65.Final Answer:
No error; output will be 65 -> Option CQuick Check:
Union last write wins = No error; output will be 65 [OK]
- Thinking union members hold values independently
- Expecting output 100 after assigning 'A'
- Assuming syntax error
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?Solution
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.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 memberv.fthat was assigned, ensuring correct interpretation.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.Final Answer:
union Value { int i; float f; char c; }; Value v; v.f = 3.14f; std::cout << v.f << std::endl; -> Option BQuick Check:
Read the same union member you wrote [OK]
- Reading a different member than assigned
- Using uninitialized union members
- Assuming union members hold independent values
Ready to prove it?
Pass the test and this pattern moves unknown
