Today, we discuss one of the most advanced topics in the list of C programming – Union.

Understanding Union in C

Union in C, is a user defined datatype that enables the user to store elements of different types into it altogether.

We can define various data members/variables within, but only one data variable can occupy the memory in the union at a time.

Thus, we can say that the** size or the memory of the union is equivalent to the size of the largest data member** present in it. So, all the data variables share the same memory location in the Union.

By this, Union provides an effective way to reuse the same amount of memory or space for multiple purposes.

With the basics covered, let’s define a Union next.


How to define a Union in C?

The union helps us define data variables that store values of different data type as shown below:

Syntax:

union union-name {
   data member1 definition ;
   data member2 definition;
   ...
   data memberN definition;
}  
  • The keyword union is used to declare a union structure.
  • Further, the union-name is the name of the union that helps us access the union throughout the program.
  • We can define multiple data members of different data types within a union.

Example:

union Info {
   int roll;
   float marks;
   char name[50];
} info_obj;  

In the above example, we have created a union ‘Info’ and defined the variables of different data types such as int, float, char, etc.

Union uses the same memory space/size to store values of different data types which increasing the reusability of the space.

The memory space of the union is the size of the largest data member declared within it.

In the above example, the largest variable ‘name’ occupies a space of 50 bytes. Thus, the union ‘Info’ would also represent a memory space of 50 bytes.


Creating Union Variables

A union variable helps the union type to allocate memory space in accordance with the largest data member.

There are two ways to create a union variable:

Method 1:

union union-name {
   data member1 definition ;
   data member2 definition;
   ...
   data memberN definition;
}  union_variable 1, union_variable2, .... , union_variableN;

Method 2:

union union-name {
   data member1 definition ;
   data member2 definition;
   ...
   data memberN definition;
};

int main()
{
  union union-name union_variable 1, union_variable2, ... ,union_variableN;
  return 0;
}

#c programming #c

Union in C - All you need to know!
1.10 GEEK