Unions in C Language | Learn C Language

C Unions

Union is a data type with two or more member similar to structure but in this case all the members share a common memory location. The size of the union corresponds to the length of the largest member. Since the member share a common location they have the same starting address. Major difference between c unions and structure is union holds same data type member while in structure different data types with elements.

C Union | Union in C | Tech-Mirror
C Union | Union in C | Tech-Mirror

The real purpose of unions is to prevent memory fragmentation by arranging for a standard size for data in the memory. By having a standard data size we can guarantee that any hole left when dynamically allocated memory is freed will always be reusable by another instance of the same type of union. This is a natural strategy in system programming where many instances of different kinds of variables with a related purpose and stored dynamically.


A union is declared in the same way as a structure declaration like..

For example, the following code declares a union data type called Employee and a union variable called emp:

It is possible to combine the declaration of union combination with that of the union variables, as shown below.

The following single declaration is equivalent to the two declaration presented in the previous example.


Example

Output :


Also Read C Structure

Leave a Reply

Your email address will not be published. Required fields are marked *