0
0
Cprogramming~5 mins

Structure vs union comparison - Quick Revision & Key Differences

Choose your learning style9 modes available
Recall & Review
beginner
What is a structure in C?
A structure is a user-defined data type in C that groups different variables under one name. Each member has its own memory location.
Click to reveal answer
beginner
What is a union in C?
A union is a user-defined data type where all members share the same memory location. Only one member can hold a value at a time.
Click to reveal answer
intermediate
How does memory allocation differ between structures and unions?
Structures allocate separate memory for each member, so total size is sum of all members (plus possible padding). Unions allocate memory equal to the largest member only.
Click to reveal answer
intermediate
Can you access multiple members of a union at the same time?
No, because all members share the same memory, changing one member overwrites others. Only one member's value is valid at a time.
Click to reveal answer
beginner
When should you use a structure vs a union?
Use a structure when you need to store multiple values simultaneously. Use a union to save memory when only one value is needed at a time.
Click to reveal answer
Which of the following is true about structures in C?
AEach member has its own memory location.
BAll members share the same memory location.
CStructures can only have members of the same type.
DStructures cannot contain other structures.
What is the size of a union in C?
ASum of sizes of all members.
BSize of the largest member.
CSize of the smallest member.
DAlways 4 bytes.
If you assign a value to one member of a union, what happens to other members?
AThey keep their previous values.
BThey cause a compile error.
CThey automatically update to the same value.
DThey become invalid or overwritten.
Which is a good reason to use a union instead of a structure?
AWhen you want to save memory and only use one value at a time.
BWhen you need to store multiple values at once.
CWhen you want to group unrelated variables.
DWhen you want to create a new data type with fixed size.
Can a structure contain a union as a member in C?
ANo, structures cannot contain unions.
BOnly if the union has one member.
CYes, structures can contain unions.
DOnly in C++ but not in C.
Explain the main differences between a structure and a union in C.
Think about how memory is used and when you want to store multiple values or just one.
You got /4 concepts.
    Describe a scenario where using a union is better than a structure.
    Imagine you have a variable that can be an int or a float but never both at once.
    You got /3 concepts.