CM304
CM304
CM304
ANDHRA PRADESH
Name : M.Subramanyam
Designation : Senior Lecturer
Branch : Computer Engg.
Institute : Q.Q.Govt.Polytechnic,Hyderabad.
Year/Semester : III Semester
Subject : UNIX & C
Subject Code : CM-304
Topic : Unions
Duration : 50 Mts
Sub Topic : Unions
Teaching Aids : PPts,Animation
CM304.81 1
Recap
Define a structure .
How to define a structure and declare structure variable?
How to initialize and assign structure members ?
How to find the size of the structure?
Is the separate memory allocated for each memory?
Is the same memory shared by all the members?
CM304.81 2
Objectives
CM304.81 3
Unions
It is a collection of variables.
Which are of different types.
It is similar to structure.
Members share the same memory location.
Memory can be saved.
CM304.81 4
Declaration
union tagname
{
datatype member1;
Members of union
datatype member2;
datatype member3;
------------------;
datatype membern;
}; End of the union
CM304.81 5
Example
union sample
{
char a;
int b;
float c;
};
CM304.81 6
Union Variable Declaration
Syntax:
union tagname
unionvariable(s);
Example
union sample u;
u is a union variable
CM304.81 7
sizeof Union Variable
b
s.a=‘A’; a A c
b
s.b=500; a A 500 c
b
s.c=55.5; a 500 55.5 c
Fig .2
CM304.81 9
Example1
CM304.81 10
Example2
CM304.81 11
Differences Between Structures and Unions
Structures Unions
Collection of elements of Collection of elements of different
different types. types.
All members can be accessed Only one member can be
at a time. accessed at a time.
sizeof structure variable is sum sizeof union variable is the
of sizes of its members. largest size of its members.
There is separate memory for There is single memory shared
each member. by all member.
CM304.81 12
Summary
In this class, you have learnt about
Union is a collection of elements of different
types.
In Union all members share the same memory
location.
Union variable is declared using keyword union.
Union members can be accessed using dot(.)
operator.
Assigning values to members.
CM304.81 13
Quiz
1)union is
b) a pointer type
c) a function type
d)none
CM304.81 14
Quiz
1)union is
b) a pointer type
c) a function type
d)none
CM304.81 15
Quiz
d)none
CM304.81 16
Quiz
d)none
CM304.81 17
Quiz
b)must be structures
CM304.81 18
Quiz
b)must be structures
CM304.81 19
Frequently Asked Questions
1. Define union.
2. Explain the declaration of a union with an
example.
3. What are the Differences between structure and
union?
CM304.81 20
Assignment
CM304.81 21