Course contentsShow
← C
Lesson 670 of 1,2199. Structures and UnionsFree lesson

Combining structs and unions

Combining structs and unions

What you'll learn: How to nest unions inside structures to create "flexible" data types that save memory and stay organized.

In C, structures (struct) are great at grouping different pieces of data together, while unions (union) are great at letting one memory space act as different things. When you combine them, you get a powerful pattern: a structure that holds common information, plus a "variable" section that changes based on the situation.

The "Swiss Army Knife" Pattern

Imagine you are building a system for a warehouse. Every item has a common ID and a weight. However, some items are liquids (measured in liters) and some are solids (measured in count).

Instead of creating a massive struct with empty fields that waste memory, you can use a union inside your struct. This creates a "specialized" slot that can be either a float or an int, but never both at once.

Implementing the Hybrid

In the example below, we use a struct to hold the "Label" of our data, and a nested union to hold the "Value." This is often called a tagged union because the type variable tells us which part of the union is currently active.

#include <stdio.h>

struct InventoryItem {
    int id;
    int type; // 0 for Liquid, 1 for Solid
    
    union {
        float liters;
        int count;
    } amount;
};

int main() {
    struct InventoryItem oil;
    oil.id = 101;
    oil.type = 0; 
    oil.amount.liters = 5.5; // We use the float member

    struct InventoryItem hammer;
    hammer.id = 202;
    hammer.type = 1;
    hammer.amount.count = 12; // We use the int member

    return 0;
}

Why do this?

By nesting the union, the InventoryItem struct only ever allocates enough space for the largest member of the union, not both. If a float and an int are both 4 bytes, the amount section only takes up 4 bytes total.

This pattern keeps your code clean. You don't have to manage two different struct types for liquids and solids; you have one master InventoryItem that adapts to your needs while keeping common data (like id) in a single, predictable place.

Key takeaway

Nesting a union inside a struct allows you to store mutually exclusive data fields while keeping common metadata organized in one place.