C – Unions

Introduction:

  • Union is a user defined data type.
  • Unions were used when memory at premium.
  • A union basically allows a variable to have more than one type; but only one of these types can be used.
Syntax:Example:
union identity
{
            Members;
} ;
union Test
{
            char c;
            short s;
};
STRUCTUREUNION
Define with struct keyword.Define with union keyword
The size of the structure is equal to the sum of the sizes of its members.The size of the union is equal to the size of the largest member.
Each member within a structure is assigned a unique storage area.Memory allocated is shared by individual members of the union.
Individual members can be accessed at a time.Only one member can be accessed at a time.
Altering the value of a member will not affect other members of the structure.Altering the value of any of the member will alter other member values.

Program to display size of union: The sum of all sizes of variables defined in structures is the size of total structure.

#include<stdio.h>
struct st{
            char a;
            short b;
            float c;
};
union un{
            char a;
            short b;
            float c;
};
int main(){
            struct st s ;
            union un u ;
            printf(“Size of structure : %d \n”, sizeof(s));
            printf(“Size of union : %d \n”, sizeof(u));
            return 0;
}

Accessing members of union: We use dot(.) operator to access the members of union.

Note: We can define any number of variables inside the union, but we cannot use multiple variables at a time. We will get odd results like follows.

#include<stdio.h>
union un{
            int a, b;
};
int main(){
            union un u ;
            u.a = 10;
            printf(“b value is : %d \n”, u.b);
            u.b = 20;
            printf(“a value is : %d \n”, u.a);
            return 0;
}
#include<stdio.h>
union un
{
            char a[2];
            int b;
};
int main()
{
            union un u ;
            u.a[0] = 2 ;
            u.a[1] = 3 ;
           
            printf(“b value is : %u \n”, u.b);
            return 0;
}
Scroll to Top