C union declaration



How to Declare Union in C ?

  1. Union is similar to that of Structure. Syntax of both are same but major difference between structure and union is ‘memory storage‘.
  2. In structures, each member has its own storage location, whereas all the members of union use the same location. Union contains many members of different types,
  3. Union can handle only one member at a time.

Syntax :

union tag
{
   union_member1;
   union_member2;
   union_member3;
   ..
   ..
   ..
   union_memberN;
}instance;

Note :

Unions are Declared in the same way as a Structure.Only “struct Keyword” is replaced with union

Sample Declaration of Union :

union stud 
{
   int roll;
   char name[4];
   int marks;
}s1;<

How Memory is Allocated ?

So From the Above fig. We can Conclude –

  1. Union Members that compose a union, all share the same storage area within the computers memory
  2. Each member within a structure is assigned its own unique storage area
  3. Thus unions are used to observe memory.
  4. Unions are useful for application involving multiple members , where values need not be assigned to all the members at any one time.