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

Defining a union with the union keyword

Defining a union with the union keyword

What you'll learn: How to create a data structure that allows different types of data to occupy the same memory location.

The One-Seat Bench

Imagine a park bench that is exactly wide enough for only one person. A tall basketball player can sit there, or a small child can sit there, or a fluffy dog can sit there. However, they cannot all sit there at the same time. If the dog jumps up, the basketball player must get off.

In C, a union is exactly like that bench. It is a custom data type that can hold different types of data (like an int, a float, or a char), but it can only hold one of those values at any given moment.

How to Define a Union

We define a union using the union keyword, followed by a name (a tag) and a block of member variables inside curly braces. This looks almost identical to a struct, but the behavior is fundamentally different.

While a struct allocates enough memory to hold all its members simultaneously, a union only allocates enough memory to hold its largest member. All members start at the same memory address.

#include <stdio.h>

// Defining the union
union DataHolder {
    int integerValue;
    float decimalValue;
    char letter;
};

int main() {
    // Declaring a union variable
    union DataHolder myData;

    // We can use it for an integer...
    myData.integerValue = 100;

    // ...or we can use it for a letter
    myData.letter = 'A'; 
    
    // Note: integerValue is now overwritten!
    return 0;
}

Why Use Unions?

You might wonder why we wouldn't just use a struct. The primary reason is memory efficiency. If you have a program that needs to track 1,000 items, and each item could be either a number or a word—but never both—a union allows you to store that information using half the space.

It is a way of telling the computer, "I need a storage locker, but I promise I will only put one specific type of equipment in it at a time."

Key takeaway

Use the union keyword to define a template where multiple members share the exact same memory space, ensuring only one member is active at a time.