Union basics - Time & Space Complexity
When working with unions in C, it's helpful to understand how the program's steps grow as data changes.
We want to see how the time to run code with unions changes when the input size changes.
Analyze the time complexity of the following code snippet.
#include <stdio.h>
union Data {
int i;
float f;
char str[20];
};
void printUnion(union Data d, int type) {
if (type == 0) printf("%d\n", d.i);
else if (type == 1) printf("%f\n", d.f);
else printf("%s\n", d.str);
}
int main() {
union Data data;
data.i = 10;
printUnion(data, 0);
return 0;
}
This code defines a union with different types and prints one value based on a type indicator.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Single function call to print a union member.
- How many times: Called once in this example.
Since the code prints one value from the union, the steps do not increase with input size.
| Input Size (n) | Approx. Operations |
|---|---|
| 10 | About 1 print operation |
| 100 | Still about 1 print operation |
| 1000 | Still about 1 print operation |
Pattern observation: The number of steps stays the same no matter the input size.
Time Complexity: O(1)
This means the program takes the same amount of time no matter how big the input is.
[X] Wrong: "Accessing different union members takes more time as the union size grows."
[OK] Correct: Accessing any member of a union is a direct operation and does not depend on the size of the union or input.
Understanding how unions work and their time behavior helps you explain memory use and efficiency clearly in interviews.
"What if we added a loop to print multiple union values? How would the time complexity change?"