C Language | Structure and Union: Union

Union

A union is a special data type available in C that allows to store different data types in the same memory location. You can define a union with many members, but only one member can contain a value at any given time. Unions provide an efficient way of using the same memory location for multiple-purpose.

Defining a Union

To define a union, you must use the keyword “union”.

union student
{
int roll;
char name[20];
float per;
};

Structures Union
Keyword “struct” is used to declare a structure Keyword “union” is used to declare a union
struct student1
{
int roll;
char name[20];
float age;
};
union student2
{
int roll;
char name[20];
float age;
};
Structure variables are declared as
Struct student1 s1;
Union variables are declared as
Union student2 s2;
Data elements of a structure are accessed using the dot(.)
operator
Example:
Struct student1 s1;
Scanf(“%d”,&s1.roll);
Scanf(“%s”,s1.name);
Scanf(“%f”,&s1.age);
Data elements of a union are accessed using the dot(.) operator
Example:
union student2 s2;
Scanf(“%d”,&s2.roll);
Scanf(“%s”,s2.name);
Scanf(“%f”,&s2.age);

 Size of a structure / structure variable is equal to the sum of the size of all data elements
Example:
Struct student1 s1;
printf(“%d”,sizeof(s1));
Output : 26

Note:in codeblocks size will be 28 as size of int is taken as 4 bytes

Size of a union / union variable is equal to the size of the largest data elements.
Example:
union student2 s2;
Printf(“%d”,sizeof(s2));
Output : 20

 

In case of structure all the data elements can be used at any point of time as they occupy different memory locations.

In case of union only one data element can be used at any point of time as they share memory locations.

The data elements of a structure occupy separate memory location

roll: 2 bytes
name: 20 bytes
age: 4 bytes

The data elements of a union share the same memory location

roll,name,age: 20 bytes

Structure occupies more memory

Union occupies less memory

Structure is used when all the data elements are required at the same time.

Union is used when only one data element is required at a time.

C Language Programming Tutorial

C Language Tutorial Home     Introduction to C Language     Tokens     If Condition      goto statement and Labelname     Switch Statements     For loop     While Loop     Do while loop     break and continue     Functions     Recursion     Inbuild Functions     Storage Classes     Preprocessor     Arrays     Pointers     Structures and Unions     File Handling     Projects