๐Ÿงฑ C Structures, Unions & Enums
Estimated reading: 3 minutes 6 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 :

Leave a Reply

Your email address will not be published. Required fields are marked *

Share

๐Ÿงฌ C Unions

Or Copy Link

CONTENTS
Scroll to Top