A union shares one memory region among multiple members—only one member is active at a time. Bit-fields pack small integers into struct bits, common in hardware registers.
Union example
union Value {
int i;
float f;
};
union Value v;
v.i = 42; /* active member is i */
Reading a different member than was last written is allowed in C but the value may be implementation-defined unless using common initial sequences carefully.
Bit-fields
struct Flags {
unsigned int ready : 1;
unsigned int mode : 3;
};
Important interview questions and answers
- Q: Union vs struct?
A: Struct lays out all members; union overlaps them—size is the largest member. - Q: When use unions?
A: Type punning for protocols, variant payloads, or embedded register views—with care for strict aliasing rules.
Self-check
- How many bytes does a union allocate?
- What are bit-fields often used for?
Interview prep
- Union vs struct?
Struct lays out all members sequentially; union members overlap—size equals largest member.