Union

Union is user-defined datatype,it is similar to the structure,but the main difference between union and structure is that,In structure each member has its own storage location and all the members of union uses a single shared memory location which is equal to the size of its largest data member.

Syntax

union [union tag]
{
member variable;
member variable;
...............................
...............................
member variable;
} [one or more union variables];


Example

union student
{
char month;
int roll_no;
float percentage;
} st1;

Structure Vs Union(on the basis of Memory)

    #include<stdio.h>
    union student
    {
      char name[30];
      int roll_no;
      float percentage;
    } st1;
    struct student1
    {
      char name[30];
      float roll_no;
      float percentage;
    }st2;
    int main( )
    {
      printf("Size of Union variable:%d\n",sizeof(st1));
      printf("Size of structure variable:%d",sizeof(st2));
      return 0;
    }

Here,the Output :-
      Size of Union variable:30
      Size of Structure variable:38
Here the size of union variable is maximum memory size of member in union and In structure size of structure variable is total memory size of member in structure.

Accessing the member of Union

We can access only one variable at a time thats why the size of union variable is maximum memory size of member in union.

    #include<stdio.h>
    union student
    {
      char name[10];
      int roll_no;
    };
    void display(union student st2)
    {
      printf("%s",st2.name);
      printf("%d\n",st2.roll_no);
    }
    int main( )
    {
      union student st1;
      printf("Enter the student name:");
      scanf("%s",&st1.name);
      printf("Enter the student Roll Number:");
      scanf("%d",&st1.roll_no);
      display(st1);
      return 0;
    }
Here the input is:-
    Enter the student name:vikas
    Enter the Roll Number:183481361
Output is:-
    Name:random words
    roll_no:183481361