What if one variable could magically change its type to fit your needs and save memory at the same time?
Why Union basics? - Purpose & Use Cases
Imagine you want to store different types of data in the same place, like a number or a letter, but you only need one at a time. Without unions, you'd have to create separate variables for each type, wasting memory and making your code messy.
Using separate variables for each data type means your program uses more memory than needed. It also makes your code longer and harder to manage, especially when you only want to store one value at a time. This can lead to confusion and bugs.
Unions let you store different data types in the same memory space, but only one at a time. This saves memory and keeps your code clean because you use one variable that can hold different types depending on the situation.
int number; char letter; // Both variables exist separately, using more memory
union Data {
int number;
char letter;
};
// One variable holds either number or letter, saving spaceUnions enable efficient memory use by allowing a single variable to store multiple types of data, one at a time.
Think of a toolbox where you can only keep one tool at a time in the same slot. Unions work like that slot, holding a hammer or a screwdriver, but never both simultaneously, saving space.
Unions let one variable hold different data types, but only one at a time.
This saves memory compared to using separate variables for each type.
They help keep code simpler and more efficient when handling multiple data types.
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 struct memory allocation
Unlike structs, unions do not allocate separate memory for each member.Final Answer:
All members share the same memory location -> Option CQuick 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 syntax
The correct syntax uses the keyword 'union', 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 A, B, and C have syntax errors or wrong keywords.Final Answer:
union Data { int i; float f; }; -> Option AQuick Check:
Correct union syntax = union Data { int i; float f; }; [OK]
- Using struct instead of union
- Using parentheses instead of braces
- Assigning values in the definition
union Number {
int i;
float f;
};
int main() {
union Number num;
num.i = 65;
printf("%c", num.f);
return 0;
}Solution
Step 1: Understand union member sharing
Setting num.i = 65 stores integer bits in union memory.Step 2: Printing num.f as char
Printing num.f with %c treats float bits as a char, causing unpredictable output.Final Answer:
Undefined behavior or garbage character -> Option DQuick Check:
Accessing different union member types = Undefined behavior or garbage character [OK]
- Expecting integer 65 to print as 'A'
- Assuming union members convert automatically
- Ignoring type mismatch in printf
union Data {
int i;
float f;
};
int main() {
union Data d;
d.i = 10;
d.f = 3.14;
printf("%d", d.i);
return 0;
}Solution
Step 1: Analyze assignments to union members
Assigning d.i then d.f means d.f overwrites the same memory used by d.i.Step 2: Understand printf output
Printing d.i after assigning d.f prints the overwritten value, not 10.Final Answer:
Assigning to d.f overwrites d.i value -> Option BQuick Check:
Union members share memory, last assignment wins = Assigning to d.f overwrites d.i value [OK]
- Thinking union members hold values independently
- Believing %d cannot print union members
- Assuming union needs initialization
int, a float, or a char in the same memory space and print the stored value correctly. Which approach using a union and an additional variable is best?Solution
Step 1: Understand union limitation
Union stores one member at a time, so we must know which member is active.Step 2: Use enum to track active member
An enum variable can track which type is stored, so printing uses correct format.Final Answer:
Use a union for data and an enum to track the active member type -> Option AQuick Check:
Union + enum for type tracking = Use a union for data and an enum to track the active member type [OK]
- Printing all union members blindly
- Not tracking which member is active
- Using separate variables wastes memory
Ready to prove it?
Pass the test and this pattern moves unknown
