Loading...
Loading...
00:00:00

What Is Union In C?

In C language, union is a special data type which allow to create a memory efficient user defined data type. Using Union we can store different type of data in same memory location. union occupies largest possible memory block size that help to store any kind of value in same data type but we can store only one type of data at once in union.

Syntax of union:

union union_name
{
    /* data variables */
}variable_name;

Union Example

union data type which has two member variables int and char . union data type occupies largest possible memory size that is int 4 bytes. we cannot assign value in union variable more than one else previous value will be distroy.

#include <stdio.h>
#include <stdlib.h>

union item
{
    int number; // 4 bytes
    char ch;    // 1 bytes
};

int main(int argc, char const *argv[])
{
    union item i1;                                           // create union variable
    i1.ch = 'P';                                             // assign value
    i1.number = 500;                                         // assign value
    printf("The value of i1.ch is %c\n", i1.ch);             // print the value of i1.ch  - unpredictable
    printf("The value of i1.number is %d\n", i1.number);     // print the value of i1.number  -500
    printf("Total Memory size occupied : %u\n", sizeof(i1)); // total size of item data type  - 4
    return 0;
}