Union Syntax & Shared Memory
A union lets several types share one block of memory. Only one member is valid at a time, and the size is the size of the largest member.
In plain English
A union is one box that different labels can use, but only one label is true at a time.
Union syntax and shared storage
A union is declared like a structure, but its members overlap in memory. Writing one member overwrites the bytes used by the others. The union's size is at least the size of its largest member, plus any alignment padding. Use a separate tag field when you need to know which member is currently active.
union Value {
int i;
float f;
char bytes[4];
};
union Value v;
v.i = 65;
printf("%d\n", v.i); /* 65 */
printf("%c\n", v.bytes[0]); /* depends on endianness */Union size and arrays of unions
An array is a homogeneous indexed collection, a structure is a heterogeneous named record, and a union shares one storage block among alternatives. A structure gives every member its own storage, so the size is the sum of the members plus padding. A union gives every member the same starting address, so the size is the largest member. Arrays of unions are useful when each element can hold one of several representations. A union can also contain an array member; only that array is valid while it is the active member.
union Number {
int i;
double d;
};
printf("%zu\n", sizeof(union Number)); /* at least 8 */Arrays of unions and array members
An array of unions stores one alternative per element. A union can also contain an array member. In that case the array shares the union storage with the other members, and only the active member is valid. This is useful for fixed-size buffers that can be viewed as bytes, characters, or integers.
union Value values[2];
values[0].i = 10;
values[1].f = 2.5f;
union Buffer {
char text[16];
int numbers[4];
};
union Buffer b;
strcpy(b.text, "hello"); /* text is active */
/* reading b.numbers now would be undefined behaviour */Key takeaways
- Union members share the same storage.
- The size of a union is the size of its largest member (plus padding).
- Only the most recently written member should be read.
- Arrays of unions store one alternative per element.
- A union can contain an array member, but only the active member is valid.
Common pitfalls
- Reading a union member other than the one last written.
- Assuming union bytes are portable across endianness.
- Confusing union size with the sum of member sizes.
- Forgetting that writing an array member overwrites the other members.
Key focus
- Compare sizeof(struct) and sizeof(union) with the same members.
- Know that a union stores one value at a time.
- Expect questions on arrays of unions and array members.
Quick check
1. What is the size of a union containing an int (4 bytes) and a double (8 bytes)?
2. How many union members can hold a valid value at the same time?