Categories
Derived Data Type

Union

A union is also a user-defined data type. It also holds members of different data types under a single name. A union sounds similar to a structure and they are similar in conceptual terms. But there are some major differences between the two. While a structure allocates sufficient memory for all its members, a union only allocates memory equal to its largest member. 

Syntax 

// define a structure.

union structure_name 

{

    data_type var1;

    data_type var2;   

};

Description of the Syntax

  • union: The union keyword is written at the beginning of the definition of a union in C. After it,  the name of the union is specified.
  • data_type: It is the data type of the member variable of the union. Members of different types can be defined inside a union.

To understand the major difference between a structure and a union, consider the following definitions of a structure and a union:

Structure definition

struct book      

{  

    int price;      // 4 bytes

    char name[10];  // 1*10 = 10 bytes    

};  

Union definition

union book      

{  

    int price;      // 4 bytes

    char name[10];  // 1*10 = 10 bytes    

};

An object of the structure book would be allocated 14 bytes for both the int and char members. However, an object of the union book would only be allocated 10 bytes (equal to the memory required by the char member) which is the maximum size.

Example

The following example illustrates union in C.

#include<stdio.h>

#include<string.h>

// define the union. 

union city

{

int pinCode;

char name[20];

};

int main( )

{

   // object of the type "city".

union city c1; 

c1.pinCode = 110090;

strcpy( c1.name, "Delhi");

   // print the information.

printf("The pin code of the city: %d\n", c1.pinCode);   

printf("The name of the city is: %s\n", c1.name); 

}

Data_Types_in_C_10

In the above example, the char array name is printed correctly whereas the pinCode gives a corrupted value. This happened because the name occupied the space allocated for object c1. 

Leave a Reply

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