C Programming - Beginner to Brilliance / Structures and Unions

Unions: Definition and Use Cases

🧾 What is a Union?

A Union in C is a user-defined data type (just like a struct) that allows storing different types of data in the same memory location.

Unlike structures, in unions:

  • All members share the same memory space.

  • Only one member can contain a meaningful value at a time.


📦 Memory Behavior of Union vs Structure

Let’s consider this example:

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

Member

Size

int i

4 bytes

float f

4 bytes

char str[20]

20 bytes

✅ Total Memory Allocated:

  • Structure = 4 + 4 + 20 = 28 bytes (plus possible padding)

  • Union = 20 bytes (only the size of the largest member)

Because in a union, all members occupy the same location, so only one value is stored at a time.


🔤 Syntax of a Union

union UnionName {
    dataType member1;
    dataType member2;
    ...
};

✅ Example:

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

📥 Accessing Union Members

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

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

int main() {
    union Data d;

    d.i = 10;
    printf("d.i = %d\\n", d.i);

    d.f = 220.5;       // overwrites 'i'
    printf("d.f = %.1f\\n", d.f);

    strcpy(d.str, "Hello"); // overwrites 'f'
    printf("d.str = %s\\n", d.str);

    return 0;
}

⚠️ Important:

  • After writing to d.f, the previous value d.i is no longer valid.

  • Only the last written member can be safely accessed.


🧠 How Does Union Actually Work?

Think of union like a container that changes its shape depending on what you put in:

  • If you put in an int, it becomes an int holder.

  • If you later put in a float, it now becomes a float holder — and previous int is lost.

Why? Because all members start at the same memory address.


🏁 Use Cases of Unions in C

When you need to store one value at a time from multiple options, union helps save space.

📦 Example:

union PaymentMethod {
    int cardNumber;
    char upiID[20];
    long walletNumber;
};

Instead of using a structure (which would take memory for all 3), union saves memory.

Used when the type of data is not fixed — common in parsing, network protocols, or data serialization.

struct Variant {
    int type;   // 1: int, 2: float, 3: char*
    union {
        int i;
        float f;
        char str[20];
    } data;
};

You check the type field to decide how to interpret data.

In low-level programming (e.g., microcontrollers), unions are used to map one memory location to multiple meanings.

Example:

union Register {
    unsigned int all_bits;
    struct {
        unsigned int flag1 : 1;
        unsigned int flag2 : 1;
        ...
    } bits;
};

This allows treating memory as a whole or bit-by-bit.

When dealing with binary data formats, sometimes you don’t know what type will be stored. Unions help with interpreting that memory correctly.


❗ Important Things to Keep in Mind

🔍 Concept

✅ Union

Memory

Only max-sized member

Simultaneous access

❌ Not safe — only 1 member at a time

Last written wins

✅ Always

Use with structures

✅ Common pattern (tag + union)

Flexible

✅ Yes

Safe access

⚠️ Only access what you last assigned


🔄 Union vs Structure — Summary Table

Feature

struct

union

Memory

Sum of all members

Size of largest member

Access

All members accessible at once

Only one at a time

Use Case

Store related data together

Store one value out of many types

Safety

Safer

Risky if misused

Efficiency

Less memory-efficient

More efficient (memory-wise)