union in c

Unions are conceptually similar to structure, that is a user-defined data type that holds data of different types(heterogeneous).

The difference between structure and unions is in terms of storage. In the case of structure, each member has its own storage location whereas in the case of unions all the elements share the same memory locations.

The size of the structure is the sum of the size of all the elements and the size of the union is the size of the largest element present in it.

Please refer to the structure in C for a better understanding of the below section.

Diag-1: Structure and union memory

Unions In C Language, Easy To Learn Unions In C Language

This implies that although union may contain many members of different types, they can store value in only one so they can be accessed.

union Emp
   char x;
   float y;

union Emp emp; // Creating a variable of union type
emp.x = 'c';
emp.y = 6.7;

They are accessed in a very similar manner to that of the structure by creating objects or union variables.

There are certain scenarios where we only want to use one of the members at a time. So in that case, using a union is a wiser option rather than using a structure. This will save us memory.

Unions allow data members who are mutually exclusive to share the same memory. This is quite important when memory is scarcer, such as in embedded systems.

The IP version can either be IPv4 or IPv6, so unions can be used to save memory.


#include <stdio.h>

Relevant Posts:

Categories: C Language

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

%d bloggers like this: