Understanding C++ union behavior in this code-reading question
This is an easy C++ question that tests your understanding of unions—a fundamental language feature that many candidates gloss over. The question asks you to trace through a code snippet and predict its output, which requires clear mental models of memory layout, member access, and type reinterpretation.
Unions are a form of data aggregation where all members share the same memory location. Unlike structs, writing to one member overwrites others. To answer this correctly, you need to reason about which value is actually stored in that shared memory at each step, and what gets printed when you access it. This tests both your knowledge of the language semantics and your ability to think spatially about memory.
- Memory layout and size of unions
- Overlapping member access and aliasing
- Endianness and type casting implications