C Unions

A union is a datastructure that can hold different data types but NOT AT THE SAME TIME. A union will contain either an instance of a type X OR an instance of a type Y. It is the programmers responsibility to make sure that on retrieval only the same type is read that was stored in the union before.

A union is therefore a polymorphic type but unlike Java or C++ the polymorphism is not taken care of by the language runtime. It is the programmers job.

   union number {  // number does NOT contain ALL
       char c;     // of i,c,f and d. Only ONE at 
       int  i;     // at time
      float f;
     double d;
   };

   union number n;
   int j;
   
   n.i = 10;
   j = n.i;  // n.d, n.f, n.c all would have been possible
             // but wrong