100% Free Forever
AI-Powered Learning
Industry Expert Content
Certificates & Badges
Learn At Your Own Pace
C

Unions in C

Learn C unions: syntax, how members share the same memory, sizeof(union) rules, and the type-punning pitfall of reading a member you did not last write.

Pointers, Structures & UnionsIntermediate12 min readJul 7, 2026
Analogies

1. Introduction

A union in C is a user-defined data type, declared similarly to a structure, whose members all share the same memory location instead of each having their own separate space. This means a union can hold only one of its members' values at any given time, making unions extremely memory-efficient when you need to represent a value that could be one of several different types but never more than one simultaneously — for example, a variant/tagged data type, low-level hardware register interpretation, or a value that is sometimes an int and sometimes a float depending on context.

🏏

Cricket analogy: A union is like a single all-purpose kit bag slot that holds either the bat or the pads at any one time, never both simultaneously, useful when a player's role, batter or keeper, is decided only at the moment of selection.

2. Syntax

A union is defined using the union keyword with syntax nearly identical to a structure: union UnionName { dataType member1; dataType member2; ... }; Variables are declared as union UnionName varName;, and members are accessed with the dot operator (.) for a direct union variable and the arrow operator (->) through a pointer to a union, exactly as with structures. The key semantic difference from a structure is memory layout: all members of a union start at the same base address and overlap each other.

🏏

Cricket analogy: Declaring a union like the team's kit locker is nearly identical syntax to declaring the equipment list structure, but unlike separate labeled shelves for bat and pads, the union's shelf is a single overlapping space where storing the bat and storing the pads both occupy the exact same spot.

3. Explanation

Because all members of a union occupy the same memory location, sizeof(union) is equal to the size of its largest member (plus any padding needed so the union's total size is a multiple of its required alignment), not the sum of all members' sizes as with a structure. Writing to one member and then reading a different member reinterprets the same underlying bytes according to the second member's type — this technique is called type punning. In strict standard C, reading a union member other than the one most recently written is technically undefined behavior, although GNU C (via GCC/Clang extensions) explicitly permits it and it is a widely used, well-understood idiom for low-level bit manipulation, such as inspecting the individual bytes of a float or checking a system's endianness. Portable, standard-conforming C code that needs guaranteed type punning should instead use memcpy() to reinterpret bytes, since that approach is well-defined in all conforming implementations. Unions are commonly paired with an explicit 'tag' field in an enclosing structure (a discriminated/tagged union pattern) so the program can track which member was last written and is therefore safe to read.

🏏

Cricket analogy: A union's size equaling its largest member is like the kit bag being sized for the bulkiest item, the bat, not the sum of bat plus pads plus gloves; storing the bat then reading it as pads is type punning, risky unless you use a well-defined method like memcpy to check the bag's actual contents, and pairing it with a tag telling you which item was last packed.

Only one member of a union is 'valid' at any given time — the one that was most recently written. Writing through one member and then reading through a different member (type punning) reinterprets the same raw bytes as a different type, which is undefined behavior under strict ISO C, even though many compilers (like GCC and Clang) explicitly document support for it as an extension and it is common in real-world systems code. If you need guaranteed portable behavior, use memcpy() to copy the bytes into the target type instead of relying on union type punning, or pair the union with a separate tag/enum field that records which member is currently valid so your own code (not the compiler) enforces correct usage.

Tip: A very common, safe use of unions is building a 'tagged union' — pair a union with an enum field in a wrapping struct, e.g. struct Value { enum { INT_T, FLOAT_T } tag; union { int i; float f; } data; };. Checking the tag before accessing data.i or data.f ensures you always read the member that was actually written.

4. Example

c
#include <stdio.h>

union Data {
    int i;
    float f;
    char bytes[4];
};

int main(void) {
    union Data d;

    d.i = 65;
    printf("After setting d.i = 65:   d.i = %d\n", d.i);

    d.f = 3.14f;              /* overwrites the same memory that held d.i */
    printf("After setting d.f = 3.14: d.f = %.2f\n", d.f);
    printf("d.i now reads garbage relative to int: %d (reinterpreted bytes)\n", d.i);

    printf("sizeof(union Data) = %zu bytes (size of largest member, float/int)\n",
           sizeof(union Data));

    /* Tagged union pattern: track which member is valid explicitly */
    struct Tagged {
        enum { INT_T, FLOAT_T } tag;
        union { int i; float f; } value;
    } t;
    t.tag = FLOAT_T;
    t.value.f = 9.5f;
    if (t.tag == FLOAT_T) {
        printf("Tagged union safely read as float: %.2f\n", t.value.f);
    }

    return 0;
}

5. Output

text
After setting d.i = 65:   d.i = 65
After setting d.f = 3.14: d.f = 3.14
d.i now reads garbage relative to int: 1078523331 (reinterpreted bytes)
sizeof(union Data) = 4 bytes (size of largest member, float/int)
Tagged union safely read as float: 9.50

/* Note: the exact integer value printed for d.i after writing d.f is
   platform/compiler dependent, since it is the raw bit pattern of the
   float reinterpreted as an int. */

6. Key Takeaways

  • All members of a union share the same memory address, so writing one member overwrites the others.
  • sizeof(union) equals the size of its largest member, unlike a struct where sizes add up (plus padding).
  • Only the most recently written member is guaranteed valid to read; reading a different member is type punning.
  • Type punning via unions is undefined behavior in strict ISO C but a documented extension in GCC/Clang and widely used in practice.
  • The tagged-union pattern (union + enum tag) is the safe, portable way to track which member currently holds valid data.

Practice what you learned

Was this page helpful?

Topics covered

#CProgrammingStudyNotes#Programming#UnionsInC#Unions#Syntax#Explanation#Example#StudyNotes#SkillVeris#ExamPrep