Writing to one union member and reading from another
suggest changeThe members of a union share the same storage. Writing to one member overwrites that storage, and reading another member reinterprets those bytes as the other member's type. When the members have the same type, as below, the value read is the value written. A member of a different type or size is not a copy of the other member: bytes outside the stored value can be indeterminate, and the reinterpreted value can be a trap representation. See Using unions to reinterpret values.
The example uses two members of the same type. Writing to m_1 makes that value appear in m_2, and writing to m_2 makes that value appear in 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
Found a mistake? Have a question or improvement idea?
Let me know.
Table Of Contents