Unions & Enumerations (enum)

⚙️ C Language 🟢 Lesson 15 of 20 📅 2026 Edition
Unions and enums are two lesser-known but genuinely useful C features. A union looks like a structure but stores its members in overlapping memory to save space, while an enum gives meaningful names to a set of related integer constants.
1Defining and Using a Union
C Language ▶ Run Code
union Data {
    int i;
    float f;
    char c;
};

int main() {
    union Data d;
    d.i = 10;
    printf("%d\n", d.i);   // 10

    d.f = 3.14;      // overwrites the SAME memory that stored d.i
    printf("%f\n", d.f);   // 3.14, but d.i is now garbage!
    return 0;
}

Unlike a structure, where every member gets its own separate memory, all members of a union share the exact same memory location. The union's total size equals only its largest member, not the sum of all members — this is the whole point of using one.

2Why Use a Union?

Unions are used when you know only one of several possible fields will be needed at any given moment, and you want to save memory rather than reserving space for all of them simultaneously — common in embedded systems and low-level protocol parsing, where every byte of memory matters.

3Defining and Using an Enum
C Language ▶ Run Code
enum Day { MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY };

int main() {
    enum Day today = WEDNESDAY;

    if (today == WEDNESDAY) {
        printf("Midweek!\n");
    }
    printf("%d\n", today);  // 2 - enums are just labeled integers
    return 0;
}

By default, an enum's values start at 0 and count upward, so MONDAY is 0, TUESDAY is 1, and so on.

4Why Enums Make Code More Readable

Compare if (status == 2) to if (status == SHIPPED) — the second version documents itself, letting anyone reading your code immediately understand what the value represents without needing to remember what each raw number means. This is the whole purpose of enums: replacing unclear "magic numbers" with meaningful names.

⚠️ Common Mistake: Reading the Wrong Field of a Union After Overwriting It

Because every field in a union shares the same memory, writing to one field and then reading a different field afterward gives you garbage, misinterpreted data — this is expected union behavior, not a bug, but it catches beginners off guard until they understand that a union only ever holds one valid value at a time.

💻 Try It Yourself

Define an enum representing order status (PENDING, SHIPPED, DELIVERED, CANCELLED) and write a program that prints a message depending on the current status.

C Language ▶ Run Code
#include <stdio.h>

enum Status { PENDING, SHIPPED, DELIVERED, CANCELLED };

int main() {
    enum Status orderStatus = SHIPPED;

    if (orderStatus == SHIPPED) {
        printf("Your order is on the way!\n");
    } else if (orderStatus == DELIVERED) {
        printf("Your order has arrived.\n");
    } else {
        printf("Order status: %d\n", orderStatus);
    }
    return 0;
}
Run This in Our Compiler →