Union is C language is the collection of different data types. It is similar to the structure except the allocation of memory for data member is different.

We can access only one member element at a time in union.

Defining a Union

Defining a Union is similar to that of structure except we use union keyword instead of struct.

Syntax of union
union union_name{
    data members;
    data members;
    ...
    ..
    data members;
}[one of more union objects];
Example
union student{
    int rollno;
    char name[20];
}s;

Accessing union data members

To access union data members we will use member access operator(.).

Program example of Union in C

#include<stdio.h>
#include<string.h>

union student{
    int rollno;
    char name[20];
};

int main()
{
    union student s;

    s.rollno = 12345;
    strcpy(s.name, "Richard");

    printf("Roll no is %d\n",s.rollno);
    printf("Name is %s\n", s.name);
    return 0;
}

output

Roll no is 1751345490
Name is Richard

If you see the output above then the output is unexpected. It is because of overwriting of the memory. Since the memory size of the union is the memory size of highest memory sized data member. In the above example the memory size of name data member is highest i.e. 20 bytes there for the size of the union is 20 bytes. But to access both the members at the same time we need 24 bytes of memory i.e memory size of rollno + memory size of name.

Accessing All the members of union

To access all the members of union we need to access one member at a time.

Program example of union in C to access all members

#include<stdio.h>
#include<string.h>

union student{
    int rollno;
    char name[20];
};

int main()
{
    union student s;

    s.rollno = 12345;

    printf("Roll no is %d\n", s.rollno);

    strcpy(s.name, "Richard");
    printf("Name is %s\n",s.name);

    return 0;
}

output

Roll no is 12345
Name is Richard