0
0
C++programming~5 mins

Structure vs union comparison in C++ - 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 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 a structure and a union?
In a structure, memory is allocated for all members separately, so total size is sum of all members. In a union, memory is shared, so size equals the largest member.
Click to reveal answer
intermediate
Can you access all members of a union at the same time?
No. Since all members share the same memory, only one member can hold a valid value at a time. Accessing others may lead to unexpected results.
Click to reveal answer
intermediate
When would you prefer a union over a structure?
Use a union when you want to save memory and only need to store one of several possible data types 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 hold one member at a time.
DStructures do not support multiple data types.
What is the size of a union in C++?
ASum of sizes of all members.
BSize of the smallest member.
CZero bytes.
DSize of the largest member.
Which statement about unions is correct?
AYou can safely store values in all members simultaneously.
BUnions allocate separate memory for each member.
COnly one member can hold a valid value at a time.
DUnions cannot contain different data types.
When is it better to use a structure instead of a union?
AWhen you want to save memory by sharing storage.
BWhen you need to store multiple values at the same time.
CWhen you only need one value at a time.
DWhen you want to restrict data types.
Which of these is a key difference between structure and union?
AUnion members share memory; structure members have separate memory.
BStructure members share memory; union members have separate memory.
CBoth share memory equally.
DNeither uses memory.
Explain the main differences between a structure and a union in C++.
Think about how memory is shared or separated and when you would use each.
You got /3 concepts.
    Describe a scenario where using a union is more efficient than a structure.
    Consider situations where only one value is needed at a time.
    You got /3 concepts.