What is a Union in C?
A union in C is a user-defined data type similar to a struct, but unlike structures where each member has its own storage location, all members of a union share the same memory location.
This means only one member can contain a value at any given time.
Syntax of Union
union union_name { data_type member1; data_type member2; ... };
Why Use a Union?
Unions in C are used primarily for efficient memory management when you need to work with multiple data types but only one at a time.
Here are the main reasons to use a union:
1. Memory Efficiency
Unions save memory because all members share the same memory space. Only enough memory is allocated to hold the largest member.
Example:
union Example { int i; // 4 bytes float f; // 4 bytes char str[20]; // 20 bytes };
Memory used: Just 20 bytes (not 28), since all members overlap.
2. Handling Variant Data
If a variable can represent different data types at different times, unions are ideal.
Example: A network packet might be a string, a float, or a structure, depending on the packet type. You can use a union to represent all formats.
3. Creating Tagged Unions (Discriminated Unions)
Use a struct with a tag and a union to represent multiple data types in a type-safe way.
#include <stdio.h> typedef struct { int type; // 1=int, 2=char union { int i; char c; } data; } Value; int main() { Value v; v.type = 1; v.data.i = 100; printf("Integer: %d\n", v.data.i); v.type = 2; v.data.c = 'A'; printf("Char: %c\n", v.data.c); return 0; }
4. Low-Level Hardware Access
- Unions allow accessing the same memory in different ways, such as bytes vs. words.
- Used in device drivers and embedded programming.
union ByteAccess { int word; char bytes[4]; };
Union Example in C
#include <stdio.h> union QuizData { int score; float duration; char grade; }; int main() { union QuizData quiz; quiz.score = 95; printf("Score: %d\n", quiz.score); quiz.duration = 2.5; printf("Duration: %.1f\n", quiz.duration); quiz.grade = 'A'; printf("Grade: %c\n", quiz.grade); // Previous values might be lost printf("After Grade assignment:\n"); printf("Score (undefined): %d\n", quiz.score); printf("Duration (undefined): %.1f\n", quiz.duration); return 0; }
Expected Output (platform-dependent for undefined values):
Score: 95 Duration: 2.5 Grade: A After Grade assignment: Score (undefined): 1094795585 Duration (undefined): 361.500000
Explanation:
- The union QuizData has three parts: an integer score, a float duration, and a character grade.
- All three parts share the same memory, so only one can safely hold a value at a time.
- The program puts values into score, then duration, and finally grade.
- Each new value replaces the one before it because they all use the same space.
- In the end, only grade shows the right value—score and duration give random or wrong results.
Best Practices When Using Unions
- Track Active Member: Always keep track of which member is currently active to avoid undefined behavior.
- Use with Enumerations: Combine unions with enums to indicate the type of data currently stored.
- Avoid Simultaneous Access: Do not attempt to access multiple members simultaneously.
- Be Cautious with Pointers: When unions contain pointers, ensure proper memory management to prevent leaks or dangling pointers.
Sanfoundry Global Education & Learning Series – 1000 C Tutorials.
- Practice BCA MCQs
- Watch Advanced C Programming Videos
- Practice Computer Science MCQs
- Apply for C Internship
- Check C Books