SyntaxPilot
Courses/C Programming/Lesson 13

C Programming · Lesson 13 of 30 · 10 min

Unions and enums

queued

These are the notes for C episode 13. Two small tools that fix two very real bugs. First, a food delivery app tells a customer their food has arrived while it is still on the road, because of a magic number; you fix it by inventing enums. Then a shop stores payments that are cash or card or UPI, never all three; a struct wastes memory, so you invent unions, see how reading the wrong member gives junk, and make them safe with a tagged union. Every example below was compiled with gcc -O2 -Wno-unused-result main.c -o main -lm (gcc 13, the same command as the SyntaxPilot compiler) and run as shown.

The problem: "Delivered! Rate your food"... but it isn't

The kitchen team stores an order's status as a number: 0 placed, 1 cooking, 2 on the way, 3 delivered. A different developer writes the app screen and thinks 2 means delivered:

#include <stdio.h>

int main() {
    int status = 2;   // kitchen: 0 placed, 1 cooking, 2 on the way, 3 delivered

    // app screen, written by someone else:
    if (status == 2) printf("Delivered! Please rate your food\n");
    else printf("Your order is being prepared\n");
    return 0;
}

Output:

Delivered! Please rate your food

The rider is still on the road. The compiler can't help: 2 is a perfectly good number.

Why it happened

  • if (status == 2): 2 what? The meaning lived only in the kitchen team's heads (and one comment).
  • A number written in code with no name to explain it is a magic number. It works like magic, until someone guesses wrong.
  • Idea: give each number a name, and only ever use the names: if (status == DELIVERED).

enum: names for numbers

Real-life example: the bank's counter board.

At the bank In C
The board names the counters: Cash, Loans, Accounts enum Status { PLACED, COOKING, ON_THE_WAY, DELIVERED };
Each name has a counter number: 0, 1, 2... C numbers them for you, starting at 0
You go by the name: "Loans counter" s == DELIVERED reads like English

An enum (short for enumeration, a numbered list) is a type whose values are named whole-number constants, called enumerators. The definition ends with ; like a struct.

#include <stdio.h>

enum Status { PLACED, COOKING, ON_THE_WAY, DELIVERED };

int main() {
    printf("%d %d %d %d\n", PLACED, COOKING, ON_THE_WAY, DELIVERED);
    enum Status s = ON_THE_WAY;
    if (s == DELIVERED) printf("Delivered! Please rate your food\n");
    else printf("Not yet. Status = %d\n", s);
    return 0;
}

Output:

0 1 2 3
Not yet. Status = 2

The right screen, and nobody had to remember what 2 means. By convention enumerators are written in CAPITALS. (typedef enum { ... } Status; gives it a short name, just like a struct in episode 12.)

Your own values

You can choose the numbers. Any enumerator without a value is "the previous one + 1":

#include <stdio.h>

enum Coin { ONE = 1, TWO = 2, FIVE = 5, TEN = 10, TWENTY = 20 };
enum Day { MON = 1, TUE, WED, THU, FRI };

int main() {
    printf("%d + %d = %d\n", FIVE, TEN, FIVE + TEN);
    printf("WED = %d, FRI = %d\n", WED, FRI);
    return 0;
}

Output:

5 + 10 = 15
WED = 3, FRI = 5

Enumerators are integers, so you can do maths and comparisons with them.

enum + switch

Enums and switch (episode 5) are best friends: one case per name.

#include <stdio.h>

enum Status { PLACED, COOKING, ON_THE_WAY, DELIVERED };

void show(enum Status s) {
    switch (s) {
        case PLACED:     printf("Order placed\n"); break;
        case COOKING:    printf("Cooking\n"); break;
        case ON_THE_WAY: printf("On the way\n"); break;
        case DELIVERED:  printf("Delivered! Rate your food\n"); break;
    }
}

int main() {
    for (enum Status s = PLACED; s <= DELIVERED; s++) show(s);
    return 0;
}

Output:

Order placed
Cooking
On the way
Delivered! Rate your food

Bonus: compile with -Wall and forget a case, and gcc warns you: warning: enumeration value 'ON_THE_WAY' not handled in switch [-Wswitch]. That's a real advantage over plain ints.

An enum inside a struct

An enum fits naturally inside last episode's struct:

#include <stdio.h>

enum Status { PLACED, COOKING, ON_THE_WAY, DELIVERED };

typedef struct {
    int id;
    enum Status status;
} Order;

int main() {
    Order o = {101, PLACED};
    while (o.status != DELIVERED) {
        o.status++;
        printf("Order %d moved to status %d\n", o.id, o.status);
    }
    if (o.status == DELIVERED) printf("Order %d: rate your food!\n", o.id);
    return 0;
}

Output:

Order 101 moved to status 1
Order 101 moved to status 2
Order 101 moved to status 3
Order 101: rate your food!

The rating screen now waits for DELIVERED, by name: the bug from the start, fixed for good.

An enum is just an int

In C, an enum variable is really an integer, and C doesn't check that it holds one of the names:

#include <stdio.h>

enum Status { PLACED, COOKING, ON_THE_WAY, DELIVERED };

int main() {
    enum Status s = 42;
    printf("s = %d\n", s);
    return 0;
}

Output:

s = 42

No error, no warning. Always assign enum variables from their names. (C++ is stricter: its enum class refuses a plain number.)

Two enums can't share a name

All enumerators live in one shared name space:

enum Light { RED, GREEN };
enum Signal { STOP, RED };
main.c:4:21: error: redeclaration of enumerator 'RED'
    4 | enum Signal { STOP, RED };
      |                     ^~~
main.c:3:14: note: previous definition of 'RED' with type 'enum Light'

Fix: give them prefixes, like LIGHT_RED and SIGNAL_RED.

enum vs #define

You may also see #define DELIVERED 3 (episode 16 covers the preprocessor). An enum is usually better: the names are grouped under one type, numbered automatically, shown by debuggers, and checked by switch warnings.

The next problem: cash, card or UPI

A shop's payment is one of:

Method What we store Type
Cash an amount float cash
Card a 16-digit number char card[17] (16 digits + '\0')
UPI an id like riya@okbank char upi[30]

With last episode's tool we'd write a struct with all three members, but every payment uses only one.

union: one shared box

Real-life example: a parking spot.

In the parking lot In C
Three separate spots (car, bike, cycle), mostly empty struct: every member has its own space
One spot for any one vehicle, sized for the biggest (a car) union: all members share the same space
Park a car and the bike that was there is gone Writing one member overwrites the others

A union looks like a struct, but all its members start at the same address and share the same bytes. Its size is the size of its biggest member (plus padding for alignment).

#include <stdio.h>

typedef struct {
    float cash;
    char card[17];
    char upi[30];
} Payment;

typedef union {
    float cash;
    char card[17];
    char upi[30];
} PayBox;

int main() {
    printf("struct: %zu bytes\n", sizeof(Payment));
    printf("union:  %zu bytes\n", sizeof(PayBox));
    return 0;
}

Output:

struct: 52 bytes
union:  32 bytes

The struct is 4 + 17 + 30 = 51, padded to 52. The union only needs room for its biggest member (30 bytes), rounded up to 32 so the float stays aligned. For a million payments that's 20 million bytes saved.

Every member starts at the same address

#include <stdio.h>

typedef union {
    float cash;
    char card[17];
    char upi[30];
} PayBox;

int main() {
    PayBox p;
    printf("cash at %p\n", (void *)&p.cash);
    printf("card at %p\n", (void *)&p.card);
    printf("upi  at %p\n", (void *)&p.upi);
    return 0;
}

Output (one example run):

cash at 0x7fffb0d8c620
card at 0x7fffb0d8c620
upi  at 0x7fffb0d8c620

Three names for one shared box.

struct union
Members stored all at once, each in its own place one at a time, all in the same place
Size sum of members (+ padding) biggest member (+ padding)
Writing a member changes only that member overwrites the others
Use when an item has all these facts an item is one of these things

Reading the wrong member

#include <stdio.h>
#include <string.h>

typedef union {
    float cash;
    char card[17];
    char upi[30];
} PayBox;

int main() {
    PayBox p;
    p.cash = 250;
    printf("cash = %.2f\n", p.cash);
    strcpy(p.upi, "riya@okbank");
    printf("upi  = %s\n", p.upi);
    printf("cash = %.2f\n", p.cash);
    return 0;
}

Output:

cash = 250.00
upi  = riya@okbank
cash = 287552338117187862528.00

The letters of the UPI id overwrote the bytes of cash, and reading them as a float gives a giant meaningless number. Worse: the union doesn't remember which member is inside, so there is no error, just junk.

Tagged unions: attach a label to the box

Put the union inside a struct, next to an enum that says what's in the box (the tag). Set the tag whenever you write; check it (with a switch) before you read. This pattern is called a tagged union (or discriminated union), and it's used everywhere from compilers to game engines and network protocols.

enum Method { CASH, CARD, UPI };

typedef struct {
    enum Method how;      // the tag: what is inside
    union {
        float cash;
        char card[17];
        char upi[30];
    } as;
} Pay;

Read a member with two dots: day[0].as.cash, or through a pointer: p->as.cash.

Common mistakes (and the real gcc messages)

Mistake What you see Why Fix
if (status == 2) No error: the wrong screen A magic number: 2 what? if (status == DELIVERED)
enum Status s = 42; No error, no warning An enum is just an int in C Assign only enum names
enum A {RED}; enum B {RED}; error: redeclaration of enumerator 'RED' Enumerators share one name space LIGHT_RED, SIGNAL_RED
Forgetting a case for an enum With -Wall: warning: enumeration value 'ON_THE_WAY' not handled in switch A state has no handling Add the case (or a default)
Writing p.upi, then reading p.cash No error: a junk number Members share the same bytes A tag + switch (tagged union)
Forgetting ; after enum {...} or union {...} error: expected ';', identifier or '(' before ... Definitions end with ; };

Mini project: a day's payments

Print a day's payments safely with a tagged union. A card is never shown in full: p->as.card + 12 is a pointer to the last 4 digits (pointer arithmetic from episode 11).

#include <stdio.h>
#include <string.h>

enum Method { CASH, CARD, UPI };

typedef struct {
    enum Method how;      // the tag: what is inside
    union {
        float cash;
        char card[17];
        char upi[30];
    } as;
} Pay;

void print_pay(Pay *p) {
    switch (p->how) {
        case CASH: printf("Cash: Rs %.2f\n", p->as.cash); break;
        case CARD: printf("Card: **** %s\n", p->as.card + 12); break;
        case UPI:  printf("UPI:  %s\n", p->as.upi); break;
    }
}

int main() {
    Pay day[3];
    day[0].how = CASH; day[0].as.cash = 250;
    day[1].how = UPI;  strcpy(day[1].as.upi, "riya@okbank");
    day[2].how = CARD; strcpy(day[2].as.card, "4111222233334444");
    for (int i = 0; i < 3; i++) print_pay(&day[i]);
    printf("Each Pay: %zu bytes\n", sizeof(Pay));
    return 0;
}

Output:

Cash: Rs 250.00
UPI:  riya@okbank
Card: **** 4444
Each Pay: 36 bytes

36 bytes = 4 for the tag + 32 for the shared box. (The card number is a made-up test number.)

What keeps it safe: every write sets the tag, every read goes through the switch. Set the tag and the value together, on the same line, so you can never forget one.

Practice

  1. enum Signal { RED, YELLOW, GREEN }: print what a driver should do for each.
  2. enum Month with values 1 to 12; print OCT and DEC.
  3. A tagged union Shape: a circle (radius) or a rectangle (width and height).
  4. Print each shape's area with a switch.
Solutions

All four in one program (verified):

#include <stdio.h>

enum Signal { RED, YELLOW, GREEN };
enum Month { JAN = 1, FEB, MAR, APR, MAY, JUN, JUL, AUG, SEP, OCT, NOV, DEC };

enum Kind { CIRCLE, RECT };
typedef struct {
    enum Kind kind;
    union {
        float radius;
        struct { float w, h; } rect;
    } as;
} Shape;

void drive(enum Signal s) {
    switch (s) {
        case RED:    printf("Stop\n"); break;
        case YELLOW: printf("Slow down\n"); break;
        case GREEN:  printf("Go\n"); break;
    }
}

float area(Shape *s) {
    switch (s->kind) {
        case CIRCLE: return 3.14159f * s->as.radius * s->as.radius;
        case RECT:   return s->as.rect.w * s->as.rect.h;
    }
    return 0;
}

int main() {
    for (enum Signal s = RED; s <= GREEN; s++) drive(s);
    printf("OCT = %d, DEC = %d\n", OCT, DEC);

    Shape a = {.kind = CIRCLE, .as.radius = 2};
    Shape b = {.kind = RECT, .as.rect = {3, 4}};
    printf("circle: %.2f\n", area(&a));
    printf("rect:   %.2f\n", area(&b));
    return 0;
}

Output:

Stop
Slow down
Go
OCT = 10, DEC = 12
circle: 12.57
rect:   12.00

Note the struct inside the union for the rectangle: a union member can be a struct, so one box holds either a radius or a width-and-height pair.

Quick quiz

What does this print?

enum Size { S = 1, M, L, XL = 10, XXL };
printf("%d %d %d", M, L, XXL);
  • A. 1 2 11
  • B. 2 3 11
  • C. 2 3 10
  • D. 1 2 3
Answer

B: 2 3 11. S is 1, so M is 2 and L is 3. XL is set to 10, so XXL counts on from there: 11. (Verified output: 2 3 11.)

Interview questions

  • What is an enum? What value does the first enumerator get by default?
  • What is a magic number and why is it bad?
  • In C, can an enum variable hold a value that isn't one of its enumerators?
  • What is the difference between an enum and #define constants?
  • What is a union? How is it different from a struct?
  • What is the size of a union?
  • What happens if you write one member of a union and read another?
  • What is a tagged (discriminated) union? Where is it used?
  • Give a real use of unions (saving memory, reading the bytes of a value, variant types).
  • Can two enums in the same program have an enumerator with the same name?

Glossary

Term Meaning Example
Magic number A number in code with no name explaining its meaning if (status == 2)
Enum (enumeration) A type made of named integer constants enum Status { PLACED, ... };
Enumerator One name inside an enum DELIVERED
Default enum values First is 0, each next one is the previous + 1 PLACED = 0, COOKING = 1
Explicit value An enumerator given its own number TEN = 10
Name space (of enumerators) All enumerators share one set of names, so they can't repeat two REDs clash
-Wswitch gcc warning (part of -Wall) for enum values missing from a switch forgetting ON_THE_WAY
Union A type whose members all share the same memory union { float cash; char upi[30]; }
Size of a union The size of its biggest member, plus padding PayBox is 32 bytes
Padding Extra bytes added for alignment 51 → 52, 30 → 32
Tag An enum member that records which union member is valid how in Pay
Tagged union A struct holding a tag and a union; read only what the tag says Pay
Anonymous struct/union member A struct or union defined right inside another, without a separate name struct { float w, h; } rect;

Summary

  • A magic number hides its meaning; an enum gives whole numbers names (from 0, or your own values).
  • Enums make switch read like English, and -Wall warns about missing cases.
  • In C an enum is just an int: nothing stops s = 42, and enumerator names must be unique.
  • A union puts all its members in one shared box, as big as the biggest member.
  • Writing one member overwrites the others, and a union doesn't remember which is inside.
  • A tagged union (an enum tag + a union inside a struct) makes it safe: set the tag when writing, switch on it when reading.

Next episode: Dynamic memory: malloc, calloc, realloc and free, memory you ask for while the program runs.