Unit-4 Union
Unit-4 Union
Union {
C}
Programmin
g
What is Union?
Union is a user defined data type similar like Structure.
It holds different data types in the same memory location.
You can define a union with various members, but only one member can hold a
value at any given time.
Union provide an efficient way of using the same memory location for multiple-
purpose.
Syntax to Define and Access Union
Declaration of union must start with the keyword union followed by the union
name and union’s member variables are declared within braces.
Syntax
1 union union_name union_name is name of custom type.
2 {
3 member1_declaration;
4 member2_declaration;
memberN_declaration is individual member
5 ...
declaration.
6 memberN_declaration;
7 };
Accessing the union members:
You need to create an object of union to access its members.
Object is a variable of type union. Union members are accessed using the dot operator(.)
between union’s object and union’s member name.
Syntax
1 union union_name union_variable;
Example to Define Union
Example
1 union student
2 {
3 char name[30]; // Student Name
4 int roll_no; // Student Roll No
5 float CPI; // Student CPI
6 int backlog; // Student Backlog
7 } student1;
Thank you