Union:
- The union is a derived data type and it is declared like structure.
- The difference between union and structure is in terms of storage.
- In structure, each member has its own storage location, whereas all the members of the union use the same location, although the union may contain many members of different types.
- When we use union the compiler allocates a piece of storage that is large enough to hold.
Name = 30 byte
Roll_num= 2 byte(int data tpe alway take 2 bytes)
Total bytes=32
The structure was taking 32 bytes but the union take
the only a maximum number of 30 bytes and use that place.
Syntax:
union union _name
{
data_type variable_name
1;
data_type variable_name
2;
.................................
.................................
data_type
variable_name n;
};
union union _name short_name;
union union _name
{
data_type variable_name
1;
data_type variable_name
2;
.................................
.................................
data_type
variable_name n;
};
union union _name short_name;
Example program union:
Output:
#include<stdio.h>
#include<conio.h>
//Union
declaration
union std
{
int
roll_num,t,e,m,s,so,tot;
char name[30];
float avg;
};
union std s;//union
short name declare
void main()
{
clrscr();
printf("\nEnter
student roll number : ");
scanf("%d",&s.roll_num);//calling structure varaiable via
union short
name
printf("\nEnter
student name : ");
scanf("%s",&s.name);
printf("\nEnter
student five subject mark: ");
scanf("%d %d %d %d
%d",&s.t,&s.e,&s.m,&s.s,&s.so);
s.tot=s.t+s.e+s.m+s.s+s.so;
printf("\nTotal
mark: %d ",s.tot);
s.avg=s.tot/5;
printf("\nAverage
mark: %f ",s.avg);
getch();
}
#include<stdio.h>
#include<conio.h>
//Union
declaration
union std
{
int
roll_num,t,e,m,s,so,tot;
char name[30];
float avg;
};
union std s;//union
short name declare
void main()
{
clrscr();
printf("\nEnter
student roll number : ");
scanf("%d",&s.roll_num);//calling structure varaiable via
union short
name
printf("\nEnter
student name : ");
scanf("%s",&s.name);
printf("\nEnter
student five subject mark: ");
scanf("%d %d %d %d
%d",&s.t,&s.e,&s.m,&s.s,&s.so);
s.tot=s.t+s.e+s.m+s.s+s.so;
printf("\nTotal
mark: %d ",s.tot);
s.avg=s.tot/5;
printf("\nAverage
mark: %f ",s.avg);
getch();
}