C Language Unions Writing to one union member and reading from another


Example

The members of a union share the same space in memory. This means that writing to one member overwrites the data in all other members and that reading from one member results in the same data as reading from all other members. However, because union members can have differing types and sizes, the data that is read can be interpreted differently, see http://www.riptutorial.com/c/example/9399/using-unions-to-reinterpret-values

The simple example below demonstrates a union with two members, both of the same type. It shows that writing to member m_1 results in the written value being read from member m_2 and writing to member m_2 results in the written value being read from member m_1.

#include <stdio.h>

union my_union /* Define union */
{
    int m_1;
    int m_2;
};

int main (void)
{
    union my_union u;             /* Declare union */
    u.m_1 = 1;                    /* Write to m_1 */
    printf("u.m_2: %i\n", u.m_2); /* Read from m_2 */
    u.m_2 = 2;                    /* Write to m_2 */
    printf("u.m_1: %i\n", u.m_1); /* Read from m_1 */
    return 0;
}

Result

u.m_2: 1
u.m_1: 2