Sunday, October 10, 2010

Union in C

Union is one of the coolest properties of C. Union is used to group a number of variables of different type in single unit like structure does.

But the differences between structure and union are:
  • While a structure enables us to treat the unit as a number of different variables stored at different places in memory, a union enables us to treat the same space in memory as a number of different variables. i.e a union permits a section of memory to be treated as a variable of one type on one occasion, ans as a different variable of a different type on another occasion.
  • A union allocates the memory equal to the maximum memory required by the member of the union while a  structure allocates the memory equal to the total memory required by the members.
  • In union, one block is used by all the member of the union but in case of structure, each member have their own memory space.
Syntax:
union test
{
      char var1;
      int var2;
      float var3;
};

example:
//union.c - A program demonstrating the concept of union
//By Nikunj Master, Eleiss
#include <stdio.h>
union test
{
      char a;
      int b;
};
int main()
{
      union test t;
      t.b=100;
      printf("t.a:%c, t.b:%d\n",t.a,t.b);
      return 0;
}

Compile the above program as:
gcc -g union.c -o union

Run as:
./union

Output:
t.a:d, t.b:100