Union in C


What is a Union

Union is user defined data type used to stored data under unique variable name at single memory location.

Union is similar to that of stucture. Syntax of union is similar to stucture.

If you know structures very well, then unions are similar to implement.

Main Difference between Union and Structure :


The major difference between structure and union is 'storage.'

In structures, each member has its own storage location, whereas all the members of union use the same location.
Union contains many members of different types, it can handle only one member at a time.

Declaration of Union :

To declare union data type, 'union' keyword is used.

Union holds value for one data type which requires larger storage among their members.

Syntax:

union union_name
{
element 1;
element 2;
element 3;
}union_variable;

Example:

union vee
{
int comp_id;
char nm;
float sal;
}vi;

In above example, it declares 'vi' variable of type union. The union contains three members as data type of int, char, float. We can use only one of them at a time.

Memory Allocation :

     C union
Fig : Memory allocation for union

To access union members, we can use the following syntax.

 vi.comp_id
vi.nm
vi.sal
That is dot operator is used as in case of structures.

Example :

#include <stdio.h>
#include <conio.h>
union vee
{
int id;
char nm[50];
}vi;


void main()
{
clrscr();
printf("\n\t Enter developer id : ");
scanf("%d", &vi.id);
printf("\n\n\t Enter developer name : ");
scanf("%s", vi.nm);
printf("\n\n Developer ID : %d", vi.id);//Garbage
printf("\n\n Developed By : %s", vi.nm);
getch();
}

Output :


 Enter developer id : 101

Enter developer name : technowell

Developer ID : 25972

Developed By : technowell


     Prev                                                   NEXT

0 comments:

Post a Comment