C Programming
Topperworld.in
Union
Union can be defined as a user-defined data type which is a collection of
different variables of different data types in the same memory location.
The union can also be defined as many members, but only one member can
contain a value at a particular point in time.
Union is a user-defined data type, but unlike structures, they share the same
memory location.
1. struct abc
2. {
3. int a;
4. char b;
5. }
In the above code is the user-defined structure that consists of two
members, i.e., 'a' of type int and 'b' of type character.
When we check the addresses of 'a' and 'b', we found that their addresses
are different.
Therefore, we conclude that the members in the structure do not share the
same memory location.
When we define the union, then we found that union is defined in the same
way as the structure is defined but the difference is that union keyword is
used for defining the union data type, whereas the struct keyword is used
for defining the structure.
The union contains the data members, i.e., 'a' and 'b', when we check the
addresses of both the variables then we found that both have the same
addresses. It means that the union members share the same memory
location.
Why do we need C unions?
Consider one example to understand the need for C unions. Let's consider a
store that has two items:
©Topperworld
C Programming
o Books
o Shirts
Store owners want to store the records of the above-mentioned two items
along with the relevant information. For example, Books include Title,
Author, no of pages, price, and Shirts include Color, design, size, and price.
The 'price' property is common in both items. The Store owner wants to store
the properties, then how he/she will store the records.
Difference between C Structure and C Union
The following table lists the key difference between the structure and union
in C:
Structure Union
The size of the structure is equal to or
The size of the union is the
greater than the total size of all of its
size of its largest member.
members.
Only one member can
The structure can contain data in multiple
contain data at the same
members at the same time.
time.
It is declared using the union
It is declared using the struct keyword.
keyword.
Let’s, see the difference with the help of example:
#include <stdio.h>
union unionJob
{
//defining a union
char name[32];
float salary;
int workerNo;
©Topperworld
C Programming
} uJob;
struct structJob
{
char name[32];
float salary;
int workerNo;
} sJob;
int main()
{
printf("size of union = %d bytes", sizeof(uJob));
printf("\nsize of structure = %d bytes", sizeof(sJob));
return 0;
}
Output:
size of union = 32
size of structure = 40
©Topperworld