๐Ÿงฑ C Structures, Unions & Enums
Estimated reading: 3 minutes 281 views

C Unions โ€“ Efficient Memory Sharing in C


Introduction โ€“ What Is a Union in C?

In C programming, a union is a user-defined data type that allows multiple members to share the same memory location. While similar in syntax to a struct, a union stores only one value at a time, making it ideal for memory-constrained environments or scenarios where only one field is needed at any given moment.

In this guide, youโ€™ll learn:

  • The syntax and behavior of unions
  • How they differ from structures
  • Real-world examples and memory advantages
  • Best practices and use cases

Core Concept โ€“ How a Union Works

All members of a union occupy the same memory space, and its total size is equal to the size of its largest member. Assigning a value to one member overwrites the data of the others.

Syntax:

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

Only one member should be used at a time.


Code Examples โ€“ Using Unions

Example 1: Accessing Union Members

#include <stdio.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 = 3.14;
    printf("d.f = %.2f\n", d.f);

    strcpy(d.str, "C Language");
    printf("d.str = %s\n", d.str);

    return 0;
}

Output (varies):

d.i = 10
d.f = 3.14
d.str = C Language

After assigning to d.str, previous values (d.i and d.f) become overwritten/undefined.


Use Cases of Unions

Use CaseWhy Use Union?
Variant data typesStore different types in the same memory
Embedded systemsSave memory in small devices
Protocol parsersInterpret memory differently (byte/word)
Interfacing with hardwareAccess data registers as multiple formats

Union vs Structure

FeatureStructure (struct)Union (union)
Memory usageSum of all membersSize of largest member
Simultaneous accessMultiple membersOnly one member at a time
Use caseGroup related dataSave space when only one field used

Best Practices & Tips

Best Practice:
Use unions in scenarios where only one member is active at a time.

Tip:
Combine union with struct or enum to create tagged unions (safe type tracking).

Pitfall:
Reading from a union member that wasnโ€™t last written to results in undefined behavior.


Real-World Applications

  • Compiler construction (AST nodes, token values)
  • Device drivers and register-level programming
  • Communication protocols (packet layout interpretation)
  • Game engines (variant object states)

Summary โ€“ Recap & Next Steps

Unions are powerful tools for optimizing memory when working with exclusive-use variables. While similar to structs in declaration, their behavior makes them suited for specialized scenarios.

Key Takeaways:

  • Unions share memory between all members
  • Only one member holds valid data at a time
  • Best for memory-saving and low-level access
  • Use carefully to avoid overwriting or reading stale data

Real-World Relevance:

Crucial in embedded development, memory-mapped IO, network parsers, and binary format interpreters.


Frequently Asked Questions (FAQ)

What is a union in C?

A user-defined type where all members share the same memory location, allowing only one active value at a time.


How is union different from structure?

A struct stores all members simultaneously; a union stores one at a time, reusing memory.


What happens if I access a union member that wasnโ€™t last assigned?

You get undefined behavior. Only the last assigned member is guaranteed valid.


Can unions be nested inside structures?

Yes. You can create complex types by combining unions and structs.


When should I use a union?

When only one of several members is used at any time and memory efficiency is important.


Share Now :
Share

๐Ÿงฌ C Unions

Or Copy Link

CONTENTS
Scroll to Top