×

C - UNION


In this chapter, we will understand about Unions.

What is Union in c?

Unions are C variables whose syntax look similar to structures, but act in a completely different manner. A union is a variable that can take on different data types in different situations.

Following is the syntax of declaring a Union

syntax
union union_name
{
  datatype1 member_name1;
  datatype2 member_name2;
  datatype3 member_name3;
          :
          :
          :
};

union is the keyword used to declare a union datatype in c. Union members are the variables of different types.


Following code declares an Union datatype called Networks and a Union variable called mobile.

Example 1: Union Declaration
// Union Data Type Network
union Networks
{
  float jio;
  int airtel;
};
int main(){
// Union variable mobile
   union Networks mobile;
}

Memory allocation of Unions

Once a union variale has been declared, the amount of memory reserved is just enough to be able to represent the largest member.(Unlike a structure where memory is reserved for all members)

In Example 1, 4 bytes of memory is set aside for the union variable mobile, since the largest member is a float in terms of memory allocation, the union variable mobile will take up 4 bytes(size of float type) in the memory.

Data stored in a union memory can be the data associated with any of its members. But only one member of a union can contain valid data at a given point in the program.

It is user's responsibility to keep the track of the data that has been most recently stored in the union variable.

Example 2: Unions variable declaration
#include <stdio.h>

void main(){
    union networks{
        int jio;
        float airtel;
    }mobile;

    mobile.jio=399;  // statement 1
    printf("Jio:%d Airtel:%f\n", mobile.jio, mobile.airtel);

    mobile.airtel=349.69856; // statement 2
    printf("Jio:%d Airtel:%f\n", mobile.jio, mobile.airtel);
}
Output
  Jio:399           Airtel:0.000000
  Jio:1135532394    Airtel:349.698547

After Statement 1

Data stored in mobile is a integer, and float member is junk.

After Statement 2

Data stored in mobile is a float, and integer member is meaningless.

Difference between Union and structure

Structure :

Example : structure variable declaration
struct id
{
  char color[12];
  int size;
}shirt;

A total of 12 bytes for character array and 2 bytes for integer = 14 bytes would be allocated to above structure. Any member of the structure can be accessed at any time.

Union :

Example : Unions variable declaration
union id
{
char color[12];
int size;
}shirt;

The space allocated to any union is large enough to hold largest of all types. Here 12 bytes ,since char array is largest of two given types. The same 12 byte is used by the char array as well as integer, thus saving space. Well the only catch in union is that programmer has to keep track of which union member is currently being used at any step.

In the next chapter, we will learn about Preprocessors.