Define Union in C Programming.
Union: Union is a special user defined data type in C Language, that stores a collection of variables having different data types at the same
memory location. a Many members can be defined in union but one member is able to store a value at a given time.Use of same memory location is provided by union for various purposes.
Syntax for Union Declaration:
In this section, we only declare the union, i.e., we only declare the union's members’ names along with their data types and name of the union. At the time of declaration memory is not allocated to the union.
union union_name {
datatype member1;
datatype member2;
...
};
Note: Union Declaration is always ends with semicolon ;
Ways to Define a Union Variable in C.
We need to define a variable of the union type to start using union members. From the Given fig. We can conclude that There are two methods using which we can define a union variable in C programming Language.
1.With Union Declaration.
2.After Union Declaration.
1. Defining Union Variable with Declaration.
union union_name
{
datatype member1;
datatype member2;
...
} variable1, variable2, ...;
2. Defining Union Variable after Declaration.
union union_name
{
datatype member1;
datatype member2;
...
};
union union_name variable1, variable2, variable3...;
where union_name is the name of an union.
Access Union Members in C language.
Union members can be accessed like structures by using (.) dot operator.
eg.
var_name1.member1;
In the given above example var name1 is the union variable and member 1 is the member of the union.
By using the the above method nested union members can also be accessed.
var_name1.member_a.member_B;
Here,
• var_name1 is a union variable.
• member_a is a member of the union.
• member_B is a member of member_a.
Initialization of Union in C
The initialization of union is the process of assigning the values to the members of a union.
The following is the syntax to assign values to union members.
var_name1.member1 = value;
Note: Only one union member can contain value at a given instance of time.