C Unions

As you know that a union is a derived data type. A union is used in a memory location that is shared by two or more different types of variables.
A union provides a way of interpreting the same bit pattern in two or more different ways.

Declare a Union in C

Declaring a union is just similar to declaring a structure. But in declaring a union, use union keyword instead of struct. Here is the general form
to define a union in C:

Here, union is a keyword, must be used in declaring a union, tag is an identifier, is simply the name of the union. And then type is any valid
data type and member_name is the name of the member. And in last union_variables is an identifier, is the name of variable, used in
accessing the union members. Here is an example:

union u_data
{
int num;
float fl;
char ch;
char str[40];
}data;

As you can see from the above declaration, a variable of u_data type can store an integer, a floating-point number, a character,
or a string of characters. In other words, a single variable i.e., the same memory location can be used to store the multiple types of data.
You can also use any built-in or user-defined data types inside a union.

Note - The memory occupied by a union will be big enough to hold the largest member of the union.

For instance, from the above union declaration, u_data type will occupy 40 bytes of memory space because this is the maximum space which
can be occupied by the character string named str.

Access Union Members in C

Use the member access operator (.) to access any member of a union. Here is the general form to access any member of a union:

union_variable.member_name;

Here is an example, showing how to access the members of the union u_data which is declared above.

data.num;
data.fl;
data.ch;
data.str;

Access and Initialize Values to Union Members in C

Here is the general form to access and initialize values to any union members in C:

union_variable.member_name = value;

Here is an example, showing how to access and initialize values to the members of the union named u_data which is declared above.