2. Unions
• AA union is a user defined data type that may holdis a user defined data type that may hold
different type of members of different sizes, BUTdifferent type of members of different sizes, BUT
only one type at a time.only one type at a time.
• All members of the union share the same
memory..
• The compiler assigns enough memory for the largestThe compiler assigns enough memory for the largest
of the member types.of the member types.
• The syntax for defining aThe syntax for defining a union and using itsand using its
members is the same as the syntax for amembers is the same as the syntax for a struct..
3. Formal Union Definition
• The general form of aThe general form of a unionunion definition isdefinition is
union tag
{
member1_declaration;
member2_declaration;
member3_declaration;
. . .
memberN_declaration;
};
wherewhere union is the keyword,is the keyword, tagtag names this kind ofnames this kind of union,,
andand mmember_declarations are variable declarationsare variable declarations
which define the members.which define the members.
Note that the syntax for defining aNote that the syntax for defining a union is exactly the sameis exactly the same
as the syntax for aas the syntax for a struct..
4. EXAMPLE OF UNION
The union of Employee is declared asThe union of Employee is declared as
union employeeunion employee
{{
int emp_id;int emp_id;
char name[20];char name[20];
float salary;float salary;
char address[50];char address[50];
int dept_no;int dept_no;
int ageint age;;
};};
6. SIMPLE PROGRAMMING EXAMPLE
#include<stdio.h>#include<stdio.h>
#include<conio.h>#include<conio.h>
union employeeunion employee
{{
char name[20];char name[20];
float salary;float salary;
}u;}u;
int main()int main()
{{
clrscr();clrscr();
printf(“enter the namen”);printf(“enter the namen”);
scanf(“%s”,&u.name);scanf(“%s”,&u.name);
printf(“enter the salaryn”);printf(“enter the salaryn”);
scanf(“%f”,&u.salary);scanf(“%f”,&u.salary);
printf(“name: %sn”,u.name);printf(“name: %sn”,u.name);
printf(“salary: %f”,u.salary);printf(“salary: %f”,u.salary);
return 0;return 0;
}}
7. Union vs. Struct
• SimilaritiesSimilarities
– Definition syntax virtually identical
– Member access syntax identical
• DifferencesDifferences
– Members of a struct each have their own address in
memory.
– The size of a struct is at least as big as the sum of the
sizes of the members.
– Members of a union share the same memory.
– The size of a union is the size of the largest member.