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 = 'A': 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
- Difference between Structure and Union in C
- Pointers in C and C++ | Set 1 (Introduction, Arithmetic and Array)
- Storage Classes in C
- Static Variables in C
- Bit Fields in C
- Enumeration (or enum) in C
- Structures in C
- Commonly Asked C Programming Interview Questions | Set 1
- Struct Hack
- How to deallocate memory without using free() in C?
- Memory Layout of C Programs
- Structure Member Alignment, Padding and Data Packing
- Operations on struct variables in C
- calloc() versus malloc()
- Understanding "extern" keyword in C
Improved By : RajeetGoyal