Like Structures, union is a user defined data type. In union, all members share the same memory location.
For example in the following C program, both x and y share the same location. If we change x, we can see the changes being reflected in y.
After making x = 2: x = 2, y = 2 After making y = 10: x = 10, y = 10
How is the size of union decided by compiler?
Size of a union is taken according the size of largest member in union.
sizeof(test1) = 4, sizeof(test2) = 4, sizeof(test3) = 40
Pointers to unions?
Like structures, we can have pointers to unions and can access members using the arrow operator (->). The following example demonstrates the same.
What are applications of union?
Unions can be useful in many situations where we want to use the same memory for two or more members. For example, suppose we want to implement a binary tree data structure where each leaf node has a double data value, while each internal node has pointers to two children, but no data. If we declare this as:
then every node requires 16 bytes, with half the bytes wasted for each type of node. On the other hand, if we declare a node as following, then we can save space.
The above example is taken from Computer Systems : A Programmer’s Perspective (English) 2nd Edition book.
Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above.
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.
- Output of C++ programs | Set 41 (Structure and Union)
- Array of Structures vs. Array within a Structure in C/C++
- Difference between NULL pointer, Null character ('\0') and '0' in C with Examples
- C/C++ program to add N distances given in inch-feet system using Structures
- Difference between Keyword and Identifier
- How to pass or return a structure to/from a Function in C/C++?
- Slack Bytes in Structures : Explained with Example
- C/C++ if statement with Examples
- Derived Data Types in C++
- Structures in C++
- Basic Code Optimizations in C
- Constants vs Variables in C language
- AKTU (UPTU) Previous Year Solved Papers | C Programming
- X-Macros in C