Union
{C}
Programming
Programming for Problem Solving (PPS)
GTU # 3110003
USING
Prof. Nilesh Gambhava
�Computer Engineering Department,�Darshan Institute of Engineering & Technology, Rajkot
What is Union?
Prof. Nilesh Gambhava
#3110003 (PPS) – Union
2
Syntax to Define and Access Union
union union_name
{
member1_declaration;
member2_declaration;
. . .
memberN_declaration;
};
1
2
3
4
5
6
7
Syntax
union_name is name of custom type.
memberN_declaration is individual member declaration.
union union_name union_variable;
1
Syntax
Prof. Nilesh Gambhava
#3110003 (PPS) – Union
3
Example to Define Union
union student
{
char name[30]; // Student Name
int roll_no; // Student Roll No
float CPI; // Student CPI
int backlog; // Student Backlog
} student1;
1
2
3
4
5
6
7
union student
{
char name[30] = “ABC”; // Student Name
. . .
} student1;
1
2
3
4
5
Example
Example
Prof. Nilesh Gambhava
#3110003 (PPS) – Union
4
Structure Vs. Union
COMPARISON | STRUCTURE | UNION |
Basic | The separate memory location is allotted to each member of the structure. | All members of the 'union' share the same memory location. |
keyword | 'struct' | 'union' |
Size | Size of Structure = sum of size of all the data members. | Size of Union = size of the largest member. |
Store Value | Stores distinct values for all the members. | Stores same value for all the members. |
At a Time | A structure stores multiple values, of the different members, of the structure. | A union stores a single value at a time for all members. |
Declaration | struct ss { int a; float f; char c }; | union uu { int a; float f; char c }; |
1 byte for c
2 bytes for a
4 bytes for f
4 bytes
f
a
c
Prof. Nilesh Gambhava
#3110003 (PPS) – Union
5
Where Union should be used?
Prof. Nilesh Gambhava
#3110003 (PPS) – Union
6
Thank you
✓