1/15
Looks like no tags are added yet.
Name | Mastery | Learn | Test | Matching | Spaced |
|---|
No study sessions yet.
What are unions for?
To define a type with multiple fields and each field occupies the same space in memory so that if you overwrite one of them in memory, they are all overwritten.
How much storage is allocated for a union?
The size of the largest field.
True or False: You can safely initialize all members of a union in-class in C++11.
False. Only the first member can have a default in-class initializer.
What is the output of the following code?
union U { int x; double y; };
U u;
u.x = 5;
std::cout << u.x;
5 — x is the active member and holds the value 5.
What happens if you read a different member of a union than the one most recently written?
The behavior is undefined; the value will likely be a reinterpretation of the shared memory.
Provide a use case where unions are particularly useful.
Memory-efficient storage of mutually exclusive data types, hardware register mapping, or type punning in low-level programming.
What will this output?
union U { int x; float y; };
U u;
u.y = 3.5f;
std::cout << u.x;
Undefined/garbled integer value; x interprets the first 4 bytes of the float y.
Can unions contain non-POD (non-Plain Old Data) types in modern C++?
Yes, since C++11, but only if they have trivial constructors, destructors, and copy/move operations.
How would you safely track which member of a union is active?
Use a separate enum or a std::variant (safer modern alternative).
True or False: All union members share the same memory location.
True. This is the defining feature of a union.
Why is understanding memory layout important?
Some CPUs require data to start at certain byte boundaries. Certain things like packets, IO, network interactions have bytes mapped to certain operations. Too much memory can cause things to be misallocated.
Why might something like this actually be 8 bytes?
struct S {
char a; // 1 byte
int b; // 4 bytes
};
Memory layout might actually be 8 bytes due to padding to align b to a 4-byte boundary. This is in order to meet a boundary and ensure that any following data is after the boundary.
What does Endian mean
order in which bytes of a multi-byte number are stored in memory
What does little-endian mean
least significant byte is stored firstW
What does big endian mean
Most significant byte is stored first