Skip to content

Union

Union is a special class that can hold different types of data in the same memory space.

cpp
int main()
{
    union
    {
        int i;
        char c;
    } u;

    u.i = 0x12345678;
    printf("%08x\n", u.i); // 12345678
    printf("%08x\n", u.c); // 00000078
}
// result has been truncated to 8 bits
// because char is 8 bits

// 0x78 is coded as 0x78 on 8 bits
// 4bits per hex digit

// each member of a union shares the same memory
// so if you change one member, you change all members

Anonymous union

cpp
int main()
{
    union
    {
        int i;
        char c;
    };

    i = 0x12345678;
    printf("%08x\n", i); // 12345678
    printf("%08x\n", c); // 00000078
}

// you can omit the name of the union
// if you don't need to access it