C Programming + Tutorials in C for Beginners

C Unions

Home  »  C Programming  »  C Unions


     Union is not new, it was originated from the Structure. In other words we can say union is similar to the structure, but processing and storage is little different. Actually union is borrowed from the structure having the same syntax and but semantics is different. Manily union is used to conserve memory. Weather union is lesser used in the C program, but for the programs having large number of statements, it is very useful. From the storage point of view, in structure each member has its own storage location, whereas in the union all the members used the same locations, So we can say union saves the memory and make the processing fast as compared to the structure.

Contents





Definition :

     A union is a variable that declares a set of multiple variable (called members or elements having different data-types) sharing the same memory area. The compiler allocates sufficient memory to hold the largest variable of the union.
All the members of union occupy the same memory locations called addresses. The old value of the already declared member will be destroyed and new value to the new member will be assigned in the memory by using the union concept.



Union Variables : The general syntax used to declare a union and union variables is written as below :
union union-tag
{
  date-type1 member-1;
  date-type2 member-2;
  date-type3 member-3;
  ......................................................;
  date-type n member-n;
}v1,v2,.......vn;

one more way of declaration be as:

union union-tag
{
  datatype-1 member-element-1;
  ......................................
  datatype-n member-element-n;
};
union tag-name v1,v2,v3,............vn;


Simple Union Program :



Output is as :

Name=Bintu
City=Muktsar




Difference between Structure and Union:
STRUCTURE
UNION
Every member has its own memoryAll members use the same memory
Keyword struct is usedKeyword union is used
All members may be initializedOnly its first member may be initialized
Different interpretations of the same memory location are not possible Different interpretations of the same memory location are possible
Consumes more space compared to unionConservation of memory is possible


<< Previous Topic
Next Topic >>



Previous
Next Post »
Thanks for your comment