7.3Unions, enums and typedef
The idea
A union stores all its members in the same bytes. Writing one member overwrites the others.
Think of it like this: One locker shared by a coat, a bag and an umbrella: you can keep only one of them in it at a time.
Why it exists
Unions test your understanding of byte-level representation and of sizeof.
How it works
- The union is as large as its biggest member.
- All members start at offset 0.
- Only the last member written has a defined value; reading another reinterprets the same bytes.
- Enums are named integer constants; typedef only renames types.
Worked example: union { int i; float f; unsigned char c[4]; }
The union takes 4 bytes. Setting i = 1078530011 makes f read as 3.14159 and shows the four bytes in c.
Now play with it
- →Type different integers into the lab and watch the same four bytes get reinterpreted.
union u { int i; float f; unsigned char c[4]; }; occupies 4 bytes, shared by all three members. Write the int and read the others (little-endian machine):
Try 1078530011: the same 32 bits are the int 1078530011 and the float 3.14159… Only the last member written is meaningful in portable C.
Check yourself
union { char c; int i; double d; } has size
Exam notes (the dense version)
All members of a union share the same memory, which is as large as its biggest member (rounded up for alignment); only the last member written has a meaningful value. An enum is a set of named int constants starting at 0 unless set. typedef gives an existing type a new name, for example typedef struct node node;.
Previous year questions: Structs, Unions & Undefined Behaviour (2)
PYQs are grouped by topic, so this is the full set for Structs, Unions & Undefined Behaviour; try the ones that match this subtopic. Open all 2 on the topic page.