Unions in C Programming (Complete Guide with Examples)
This tutorial explains unions in C, which are similar to structures but store only one member at a time in the same memory location. It covers declaration, initialization, memory efficiency, and practical examples for beginners.
1. What is a Union
- A union is a user-defined data type similar to a structure.
- All members share the same memory location, so only one member can store a value at a time.
- Useful for memory-efficient storage when only one of the members is needed at a time.
2. Syntax
3. Example: Basic Union
Sample Output:
Explanation:
- All members share the same memory
- Assigning a value to one member overwrites the previous value
4. Key Points to Remember
- Union members share memory, unlike structures where each member has its own memory
- Only one member can hold a value at a time
- Saves memory in applications where not all members are used simultaneously
- Can be combined with structures, arrays, and pointers for complex applications