Previously, We learnt about Structures in C programming,where we can store different types of data members collectively,under a same name. This Data Structure is a very good way of storing data, but what would happen if we only have a limited amount of space available, and the problem faced by us requires the implementation of Data Structures, this is where the Concept of Unions comes into play.
Unions are special User-defined Data-Types in C Programming, that helps us to store different data types at the same memory location. It works on the same concept of grouping different data types as in structures in C, but just with a little twist in terms of storage, i.e, all the members would be having the same memory location, this means, that at a time only one of the data members can contain a value. Not all like in structures.Only the greatest member of the Union will be given space in the memory.
👉 Simple elaboration in my words! 👈
Let us suppose we have to buy from a choice of 3 tubs of different capacities,1L-2L-4L,now in this case the largest tub has 4L volume. and now the 4L tub can accomodate the other tubs also, like we can store 2L of something in 4L also, we need not buy 4 1L tubs of 2 2L tubs, similar is the case with unions, supposing its members are an int variable, float and string of size 100, now the largest is 100byte string, in this 100byte we can the float vars and the int ones also, so we allocate memory to the largest variable only, to save space. Hope you are understanding what i want to say through this example, its still lame I know🤣.
Defining a Union
Unions have the same syntax as that of Structures, just the struct keyword changes with union keyword.
union union_name {
union member;
union member;
...
union member;
} union_variables;
example:
union student {
int rn;
float marks;
char name[20];
} s1;
This declares a variable of type union student, which has 3 members in it, but only one of them can be accessed at a time, because only one memory location is allocated for all of them. Thats why the compiler allocates memory for the largest variable type in the union. So that the memory is large enough to hold other smaller type variables also.
Size of the Union
In the above example, int variable has 4 bytes, float has 8 bytes and string(name) has 20 bytes, As the memory is allocated for the largest variable only,so the size of the largest variable is size of the union, so here Size of Union is 20 bytes.
* Unions are really an Memory-efficient way of storing the variables in Data Structures. Here we use same memory location for multiple purposes, without any wastage of memory.
Accessing the variables of the Union
To access the members of Union, we use the period symbol or the " . " operator. Also we can access Pointer variables using arrow( -> ) operator.
Example 1:
#include<string.h>
#include <stdio.h>
union student {
int rn;
float marks;
char name[20];
};
int main() {
union student s1;
s1.rn = 1;
s1.marks = 100;
strcpy( s1.name , "ABC");
printf("Roll number = %d\n", s1.rn);
printf("Marks = %f", s1.marks);
printf("Name is = %s", s1.name);
return 0;
}
OUPUT
Roll number = 4407873
Marks = 0.000000
Name is = ABC
* Here we can see, the value of rn and marks gets changed this is because in unions only one member can be used at one time, so the one with the last assignment is retained that is name. Because it is the only one who has memory allocated to it.
But what if we want to print all the members using Unions.
See this....
#include<string.h>
#include <stdio.h>
union student {
int rn;
float marks;
char name[20];
};
int main() {
union student s1;
s1.rn = 1;
printf("Roll number = %d\n", s1.rn);
s1.marks = 100;
printf("Marks = %f", s1.marks);
strcpy( s1.name , "ABC");
printf("Name is = %s", s1.name);
return 0;
}
OUPUT
Roll number = 1
Marks = 100.000000
Name is = ABC
* Here when we used rn variable, we accessed its value and when we came to use the other variable marks, the value of rn got corrupted . and similarly when assigning value to name, variable marks also get corrupted.
Example 2:
#include<string.h>
#include <stdio.h>
union student {
int x,y;
};
int main() {
union student s1;
s1.x = 1;
printf("Value = %d\n", s1.x);
printf("Value = %d\n", s1.y);
return 0;
}
OUTPUT
Value = 1
Value = 1
* In this case both the union member variables were of same type. and when one got initialized. The same value was stored in the other also. This is because both share the same memory location. So if one value is added to them, changes are seen in other also. As both are same.
* UNION VARIABLES DO NOT HAVE A DEFAULT VALUE, SO IF WE PRINT A UNION VARIABLE WITHOUT INITIALISING IT, IT MAY SHOW DIFFERENT OUTPUTS AT DIFFERENT TIMES.
Applications of Unions
- The primary use of a union is allowing access to a common location by different data types, for example hardware input/output access, bitfield and word sharing, or type punning.
- Unions can also provide low-level polymorphism. (source → https://en.wikipedia.org/wiki/Union_type#:~:text=The%20primary%20use%20of%20a,also%20provide%20low%2Dlevel%20polymorphism. )
- Check http://linux.die.net/man/2/epoll_ctl . It uses epoll_data union inside epoll_event. Because, it has intention to store 32-bit unsigned integer, pointers, file descriptor and 64-bit unsigned integer as data in the epoll_event. Now, you may ask that it can use 64-bit integer data straight away and store anything less than 64-bit. Well, in that case, you need to perform typecasting which will make code ugly. (source → https://www.quora.com/What-is-the-use-of-unions-in-C-real-time-where-we-use-it)
Disadvantages of Unions
- We can use only one union member at a particular time.
- All the union variables cannot be initialized or used with varying values at a time.