HOME HTML EDITOR C JAVA PHP

C Unions: Shared Memory Storage

A **Union** is a user-defined data type where all members share the same starting memory address. You can define a union with many members, but only **one member can contain a value at any given time**.

1. Defining and Declaring a Union

The syntax for a union is identical to a structure, but it uses the union keyword.

union Data {
    int i;
    float f;
    char str[20];
};

int main() {
    union Data data;
    return 0;
}

2. Memory Allocation: Struct vs. Union

This is the most critical difference between the two. A structure's size is the sum of its members' sizes, whereas a union's size is the size of its largest member.

Feature Structure Union
Keyword struct union
Memory Each member has its own location. All members share the same location.
Total Size Sum of all members. Size of the largest member.

3. Accessing Union Members

Because members share memory, changing one member will overwrite the others. You must use one member at a time to avoid data corruption.

union Data data;

data.i = 10;
printf("data.i : %d\n", data.i); // Output: 10

data.f = 220.5;
printf("data.f : %.1f\n", data.f); // Output: 220.5

// Now data.i is corrupted because data.f took its spot!
printf("data.i after f: %d\n", data.i); // Output: Garbage value

4. Practical Use Cases

5. Nested Unions

Just like structures, unions can be nested inside structures (often called "Tagged Unions") to keep track of which union member is currently active.

struct Token {
    int type; // 0 for int, 1 for float
    union {
        int iVal;
        float fVal;
    } val;
};
Pro Tip: Always use a "Type Flag" (like in the example above) when using unions in professional code. Since C doesn't tell you which union member was last updated, a flag prevents you from accidentally reading an integer as a float and getting gibberish.