Skip to main content

24. Union

 

Union in C

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.

The difference between structures and unions lies in the fact that in structure, each member has its own storage, whereas members of a union uses a single shared memory location. This single shared memory location is equal to the size of its largest data member.

When we define the union, then we found that unionis defined in the same way as the structure 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. 

Memory Allocation of Union

Considering two variables in a Union. Both the variables are sharing the same memory location and having the same initial address.
In union, members will share the memory location. If we try to make changes in any of the member then it will be reflected to the other members as well.

#include <stdio.h>
union abc{
    int a;
    char b;
}var;
int main()
{
    var.a = 66;
    printf("a = %d\n", var.a);
    printf("b = %d", var.b);
    return 0;
}

Output :

a = 66
b = 66

Deciding the size of Union

The size of the union is based on the size of the largest member of the union.

#include <stdio.h>
union deepak{
    int p;
    char q;
    float r;
    double s;
};
int main()
{
    printf("Size of union deepak is %d", sizeof(union deepak));
    return 0;
}

Output :

Size of union deepak is 8

As we know, the size of int is 4 bytes, size of char is 1 byte, size of float is 4 bytes, and the size of double is 8 bytes. Since the double variable occupies the largest memory among all the four variables, so total 8 bytes will be allocated in the memory. Therefore, the output of the above program would be 8 bytes.

Accessing members of union using pointers

We can access the members of the union through pointers by using the (->) arrow operator.

#include <stdio.h>
union hlw{
    char x;
    int y;
}hii;
int main()
{
    union hlw *ptr;
    hii.y = 90;
    ptr = &hii;
    printf("The value of y is %d", ptr->y);
    return 0;
}

Output :

The value of y is 90

Comments