Skip to main content

Documentation Index

Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt

Use this file to discover all available pages before exploring further.

A union in C is a user-defined composite data type that allows multiple members of different types to occupy the exact same memory location. Unlike a struct, where each member is allocated its own distinct memory space sequentially, a union allocates a single shared block of memory. The total size of a union is determined by the size of its largest member, potentially adjusted for memory alignment requirements. Because all members share this single memory space, a union can only hold a valid value for one of its members at any given time.

Syntax

A union is defined using the union keyword, followed by an optional tag and a block containing member declarations.
union UnionName {
    dataType member1;
    dataType member2;
    dataType memberN;
};

Memory Allocation and Sizing

When the compiler allocates memory for a union, it calculates the sizeof each member and reserves an amount of memory equal to the largest member.
#include <stdio.h>

union Data {
    int i;        // Typically 4 bytes
    float f;      // Typically 4 bytes
    char str[20]; // 20 bytes
};

int main() {
    union Data myData;
    // The size of myData will be 20 bytes (the size of 'str'), 
    // not 28 bytes (the sum of all members).
    printf("Size of union: %zu\n", sizeof(myData)); 
    return 0;
}
Note: The compiler may add padding bytes to the total size of the union to satisfy the alignment requirements of its strictest member.

Member Access and Data Overwriting

Members of a union are accessed using the dot operator (.) for direct instances, or the arrow operator (->) for pointers to a union. Because the memory is shared, writing to a new member inherently overwrites the bit pattern of the previously stored member. Reading from a member other than the one most recently written to results in undefined behavior or yields a reinterpreted bit pattern (type punning).
union Data data;

// Write to the integer member
data.i = 10; 
// Memory currently holds the integer representation of 10

// Write to the float member
data.f = 220.5; 
// The memory block is overwritten with the IEEE 754 representation of 220.5.
// The value of data.i is now corrupted/invalid.

Initialization

By default, standard C rules dictate that initializing a union with a brace-enclosed list will initialize its first declared member. To initialize a different member at the time of declaration, C99 introduced designated initializers.
// Initializes the first member (int i)
union Data d1 = { 42 }; 

// C99 Designated Initializer: Initializes the float member specifically
union Data d2 = { .f = 3.14f }; 

// C99 Designated Initializer: Initializes the string member
union Data d3 = { .str = "Hello" };

Pointers to Unions

Pointers to unions behave identically to pointers to structs. The pointer holds the base memory address of the union, which is simultaneously the base address of every single member within that union.
union Data data;
union Data *ptr = &data;

// Accessing members via pointer
ptr->i = 100;
Master C with Deep Grasping Methodology!Learn More