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 aDocumentation Index
Fetch the complete documentation index at: https://docs.syntblaze.com/llms.txt
Use this file to discover all available pages before exploring further.
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 theunion keyword, followed by an optional tag and a block containing member declarations.
Memory Allocation and Sizing
When the compiler allocates memory for a union, it calculates thesizeof each member and reserves an amount of memory equal to the largest 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).
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.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.Master C with Deep Grasping Methodology!Learn More





