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

Using unions for type punning

Using unions for type punning

What you'll learn: How to use a union to view the exact same memory through two different data types.

The "Same Box, Different Glasses" Trick

In C, a union allocates only enough memory for its largest member. Every member starts at the exact same memory address. Normally, we use this to save space, but advanced programmers use it for type punning: looking at the raw bits of one data type as if they were another.

Think of a union as a single storage box. You can put a "Float" object inside, but then look at the box through "Integer" glasses. You aren't converting the number (like casting (int)5.5 to get 5); you are peering at the raw binary 1s and 0s that make up that float.

Why do this?

Sometimes you need to manipulate data at a bit-level—such as sending a float over a network or inspecting its sign bit—without the C compiler trying to "fix" or convert the value for you.

#include <stdio.h>

union PunningBox {
    float myFloat;
    unsigned int myInt;
};

int main() {
    union PunningBox box;

    // 1. Put a float in the box
    box.myFloat = 2.0f;

    // 2. Look at it as an integer
    // This won't print "2". It prints the raw IEEE 754 binary representation.
    printf("Float value: %f\n", box.myFloat);
    printf("Raw bits as hex: 0x%X\n", box.myInt);

    return 0;
}

How it works

In the code above, the computer stores 2.0f in memory. In binary, a float 2.0 is represented as 01000000000000000000000000000000.

If we simply cast a float to an int (int x = (int)2.0f), C translates the value to the integer 2. But by using the union, we tell C: "Don't translate anything. Just show me the bits." The myInt member gives us the integer 1073741824, which is the decimal version of those raw bits.

A Note on Safety

While type punning via unions is a common pattern in C, it relies on how your specific hardware handles memory. It is a powerful "low-level" trick used in systems programming, graphics, and networking to bypass the standard rules of data types.

Key takeaway

Type punning with unions allows you to interpret the raw binary bits of one data type as another without performing a mathematical conversion.