A union overlays all its members at the same memory address, so they share storage; its size is that of its largest member, and only one member holds a valid value at a time. Uses: viewing the same bytes multiple ways (a 32-bit register as uint32_t word or uint8_t bytes[4] to extract byte lanes or inspect endianness); a "tagged union," where a struct holds a type tag plus a union of the possible payloads, so one fixed-size slot can carry any one of several message types; and memory-constrained code where two large fields are never used simultaneously. The key caveat is type-punning, writing one member and reading another reinterprets the bytes. It's defined in C but undefined in C++, and even in C, memcpy is the safer portable tool for byte reinterpretation because it sidesteps strict-aliasing concerns.
C Programming · Interview question
What is a union and when would you use one?
A strong answer
What a weak answer sounds like
You know the answer. Do you know what gets you dinged?
Pro breaks down the answer most candidates actually give to this question — and the specific reason an interviewer marks it down. It’s the difference between sounding correct and sounding senior, on all 472 questions.
From the lesson
Structs, Unions & Bitfields
Group related data, overlay the same bytes two ways, and pack flags into bits, plus the padding and alignment rules that decide sizeof and bite packet parsing.