← 🧱 Structs, Unions & Undefined Behaviour
Subtopic 3 of 4

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

  1. The union is as large as its biggest member.
  2. All members start at offset 0.
  3. Only the last member written has a defined value; reading another reinterprets the same bytes.
  4. 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):

0xdb
c[0] = 219
0x0f
c[1] = 15
0x49
c[2] = 73
0x40
c[3] = 64
u.i (int)1078530011
u.f (same bits read as float)3.1415927
sizeof(union)4 (the largest member)
if it were a struct4 + 4 + 4 = 12 bytes

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

Remember: Union size = largest member; members share storage.
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.