C Unions

C Unions: Memory Efficient Data Structures

While C structs allow you to group distinct data types together where each member has its own dedicated memory space, Unions provide a completely different approach. In a union, all members share the exact same memory location.

Unions are advanced constructs used primarily in systems programming, embedded systems, and network packet parsing, where memory conservation is absolutely critical. This detailed guide will walk you through declaring, using, and mastering unions in C to optimize your applications.


1. What is a Union?

A union is a user-defined data type similar to a structure. The key difference is memory allocation.

Because memory is shared, only one member can contain a valid value at any given time.


2. Defining and Declaring a Union

You define a union using the union keyword, followed by the union tag and its members enclosed in curly braces.

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

In the above example, the size of union Data will be 20 bytes. Why? Because the largest member is str[20], which takes 20 bytes. i (4 bytes) and f (4 bytes) will safely fit within this 20-byte block.


3. Accessing Union Members

Just like structures, you use the dot operator (.) to access members of a union. However, you must be extremely careful to only read from the member that was most recently written to.

Proper Union Usage

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

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

int main() { union Data data; // Using one member at a time data.i = 10; printf("data.i : %d\n", data.i); data.f = 220.5; printf("data.f : %.1f\n", data.f); strcpy(data.str, "C Programming"); printf("data.str : %s\n", data.str); return 0; }

Notice how we assign and immediately print each member? This ensures data integrity.


4. The Pitfall: Data Overwriting

If you attempt to assign values to all members at once and then read them, you will encounter data corruption. Because they share memory, writing to a new member overwrites the data of the previous member.

Data Corruption Example

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

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

int main() { union Data data; // Assigning all at once data.i = 10; data.f = 220.5; strcpy(data.str, "C Programming"); // The integer and float values are now corrupted! printf("data.i : %d\n", data.i); // Garbage value printf("data.f : %f\n", data.f); // Garbage value printf("data.str : %s\n", data.str); // Valid value return 0; }


5. Practical Use Cases for Unions

Why use unions if they are so restricted?

  1. Memory Conservation: In embedded systems with minimal RAM, unions help reuse variables that are never active simultaneously.
  2. Type Punning: Reading the same memory block as different data types (e.g., reading a float bit-by-bit as an int).
  3. Variant Records: Implementing structures where a field's data type depends on a previously read "tag" or "type" indicator.

Exercise 1 of 1

?

How is the total memory size of a union determined?