Unions & Enumerations (enum)

🔵 C Programming Lesson 12 Intermediate

Unions are memory-optimizing structures where all member fields share the same memory space. Enumerations (enums) define custom lists of named integer constants to make code more readable.

1 Structs vs. Unions (Shared Memory Space)

While a `struct` allocates separate memory space for each of its fields, a **`union`** allocates a single shared memory block sized to match its **largest member**. Modifying one union field overwrites all other fields, meaning only one field can be actively stored at any given time. This is useful for optimizing memory-constrained systems.

2 Enumerations for State Flags

Enums bind names to integer constants behind the scenes, defaulting to index numbers (0, 1, 2...). Let's compare unions and enums in code:

C — Unions and Enums ▶ Run Code
#include <stdio.h>

union Data {
    int i;
    float f;
};

// Enum defining status flags
enum Status {
    PENDING,  // gets index 0
    SUCCESS,  // gets index 1
    FAILED    // gets index 2
};

int main() {
    union Data d;
    
    d.i = 10;
    printf("Stored int: %d\n", d.i);
    
    // Writing to float overwrites the shared memory space!
    d.f = 220.5f;
    printf("Stored float: %.2f\n", d.f);
    printf("Int value corrupted: %d\n", d.i); // Corrupted representation

    // Enum evaluation
    enum Status current = SUCCESS;
    if (current == SUCCESS) {
        printf("Transaction finished successfully (Status Code: %d)\n", current);
    }

    return 0;
}
3 Code Challenge
Challenge: Write a union called `Number` that can store either an `int` or a `double`. Set values for both sequentially, printing them immediately after assignment to confirm they represent the correct values before being overwritten.