Union is a user defined data type which store heterogeneous/different types data
item or element in a single variable. It is a Combination of primitive and derived data type.
or
A Union is a collection of one or more data items of different data types, grouped together under a single name.
Variables inside the Union are called members of Union. Each element of a Union is called a member.
union keyword is used to define/create a Union. union define a new data type which is
a collection of different type of data.
Syntax
union Union_name /tag name
{
data_type varialbe1;
data_type varialbe2;
.
.
data_type varialben;
};
Note: Don't forget the semicolon }; in the ending line.
Example
union teacher
{ int eid;
char name[50];
float salary;
char subject[20];
};
Union can be declared above main or in side the main function. If Union is declared above main function that Union is a global Union then it can be accessible anywhere within the program. If it is declared in main function or any user defined function then it becomes a local Union whose scope is within the function only.
In order to access the Union members first the Union variable is declared. The syntax of Union variable
declaration is as follows
union unionname unionvariable;
ex : union teacher t1;