UNION
Union is a
collection of non-homogeneous / heterogeneous / different data type elements
that can be grouped together under a common name. Union is also a user-defined data type which is similar to structure.
The general format of a union
declaration is:
Syntax : union
Tag
{
Datatype
Member1;
Datatype
Member2;
-
- -
-
- -
Datatype
Membern;
};
Where,
Ø union is a keyword used to
declare the union data type.
Ø Tag is name the union that
follows same rules as a valid identifier.
Ø Members declared inside the
union are known as union members (or) union elements.
Ø Union declaration must be
ended with a semicolon.
Example:
union
employee
{
int Id;
char
Name[25];
long
Salary;
};
Memory is allocated for the union only at the
time of creating union variable. The
general form of creating union variables is:
Syntax : union Tag Variable1, Variable2, - - - - - , Variablep;
Example : union
employee E;
For this, the memory
allocation will be:
Ø In union, compiler selects
the member which occupies highest memory, and that memory is reserved
only. So, that all the members of the
union are shared that common memory. It
implies that, although a union may contain many members of different types, it
can handle only one member at a time.
Ø Dot operator is used to
access member of the union with the union variable. The general format of accessing union members
with union variable is:
#include<stdio.h>
union employee
{
int Id;
char Name[25];
long Salary;
};
void main()
{
union employee E;
printf("\nEnter
Employee Id : ");
scanf("%d",
&E.Id);
printf("\n\n Employee Id : %d", E.Id);
fflush(stdin);
printf("\nEnter
Employee Name : ");
scanf("%s",
&E.Name);
printf("\n Employee Name : %s", E.Name);
printf("\nEnter
Employee Salary : ");
scanf("%ld",
&E.Salary);
printf("\n Employee
Salary : %ld", E.Salary);
}
No comments:
Post a Comment