Structure vs union comparison - Performance Comparison
Let's see how the time it takes to compare two data containers changes with their size.
We want to know how comparing structures and unions grows as their content grows.
Analyze the time complexity of the following code snippet.
struct Data {
int a;
int b;
int c;
};
union Value {
int x;
float y;
char z[4];
};
int compare_struct(struct Data s1, struct Data s2) {
return (s1.a == s2.a) && (s1.b == s2.b) && (s1.c == s2.c);
}
int compare_union(union Value u1, union Value u2) {
return u1.x == u2.x;
}
This code compares two structures by checking all fields, and two unions by checking only one shared field.
Identify the loops, recursion, array traversals that repeat.
- Primary operation: Comparing each field in the structure one by one.
- How many times: Once per field (3 times here), for the structure; only once for the union.
As the number of fields in the structure grows, the number of comparisons grows too.
| Number of Fields (n) | Approx. Comparisons |
|---|---|
| 3 | 3 |
| 10 | 10 |
| 100 | 100 |
Pattern observation: The time to compare structures grows directly with the number of fields.
Time Complexity: O(n)
This means comparing structures takes longer as they have more fields, growing in a straight line with size.
[X] Wrong: "Comparing unions takes the same time as structures because they look similar."
[OK] Correct: Unions share the same memory for all fields, so only one field needs comparison, making it faster.
Understanding how data layout affects comparison time helps you write efficient code and explain your choices clearly.
"What if the structure had nested structures inside? How would that affect the time complexity of comparison?"
Practice
struct and a union in C?Solution
Step 1: Understand struct memory allocation
A struct allocates separate memory for each member, so all members exist independently.Step 2: Understand union memory allocation
A union uses the same memory location for all members, so only one member can hold a value at a time.Final Answer:
A struct stores all members separately, while a union shares the same memory for all members. -> Option BQuick Check:
Struct = separate memory, Union = shared memory [OK]
- Thinking union stores all members separately
- Confusing struct and union memory sharing
- Assuming both behave the same in memory
Data with an int and a float member?Solution
Step 1: Recall union syntax
The correct syntax uses the keywordunion, followed by the name and braces containing members separated by semicolons.Step 2: Check each option
union Data { int i; float f; }; matches the correct syntax. struct Data { int i; float f; }; usesstructinstead ofunion. union Data ( int i; float f; ); uses parentheses instead of braces. union Data = { int i; float f; }; uses an equals sign incorrectly.Final Answer:
union Data { int i; float f; }; -> Option DQuick Check:
union syntax = keyword + name + braces + members [OK]
- Using struct keyword instead of union
- Using parentheses instead of braces
- Adding equals sign in definition
union Data {
int i;
float f;
};
int main() {
union Data d;
d.i = 10;
d.f = 3.14;
printf("%d", d.i);
return 0;
}What will be the output?
Solution
Step 1: Understand union member assignment
Assigningd.i = 10;stores 10 in the union memory. Thend.f = 3.14;overwrites the same memory with the float value.Step 2: Check the printf output
Printingd.iafter assigningd.freads the memory as int, but the memory holds float bits, causing undefined or garbage output.Final Answer:
Undefined or garbage value -> Option AQuick Check:
Union stores one value; last assignment wins [OK]
- Expecting both values to be stored
- Printing float as int correctly
- Ignoring memory overwrite in union
struct Point {
int x;
int y;
};
union Point {
int x;
int y;
};
int main() {
struct Point p1 = {1, 2};
union Point p2;
p2.x = 3;
p2.y = 4;
printf("%d %d", p1.x, p1.y);
printf("%d %d", p2.x, p2.y);
return 0;
}Solution
Step 1: Check struct and union naming rules
In C, struct and union tags share the same namespace. Defining both with the same namePointcauses a redefinition error.Step 2: Verify other statements
Union members can be assigned values. Struct initialization with braces is valid. printf can print multiple variables with format specifiers.Final Answer:
Cannot define struct and union with the same name in the same scope. -> Option AQuick Check:
Struct and union tags must have unique names [OK]
- Thinking union members can't be assigned
- Believing struct brace initialization is invalid
- Assuming printf can't print multiple values
Solution
Step 1: Analyze memory needs
Since only one value (ID or score) is needed at a time, saving memory is important.Step 2: Choose between struct and union
A struct stores both values separately, using more memory. A union shares memory for all members, storing only one value at a time, saving memory.Final Answer:
Use a union because it shares memory and stores only one value at a time. -> Option CQuick Check:
One value at a time + memory saving = union [OK]
- Choosing struct and wasting memory
- Using separate variables unnecessarily
- Using array which doesn't fit this need
Ready to prove it?
Pass the test and this pattern moves unknown
