Unions provide different ways of looking at the same memory location.
To understand this let us consider the role of types in defining variables.
Types enable us to look at an allocated memory block from a particular
well defined perspective. I have defined an integer i as follows.
short int i;
This definition results in allocation of two bytes in memory.
The type "int" tells our program on how to interprete the binary data
in the two bytes allocated for i. In C the program will look at these
two bytes as having a 16 bit 2's compliment number. Type int gives
semantics to the allocated memory block. Our two bytes could have been
viewed in innumerable ways, but, type int constraints our
way of looking.
Unions are UDTs( User Defined Types) they allow multi-perspective
viewing of the same memory block. You list the types in Unions and
then you can bind any of the listed type to your variable.
This results in a variable with polymorphic type.
Take an example of a union declared in C.
union xyz
{
float x;
int y[2];
char z[4];
} u1;
The variable u1 when allocated in memory has typically 4 bytes.
These 4 bytes can be accessed in three ways. Making the memory
type polymorphic.
If accessed via u1.x the memory is treated by compiler as a float.
If accessed via field y say u1.y[1] , the last two bytes of the
memory are treated an integer.Similarly through array field z
the same memory can be viewed as an array of characters.
This can be very serious in compilers which are strict in type
checking . You get an official way of breaking the strict type
checking rules.
One more example will drive the point home ( concocted java code)
class PQR { ... }
union dangerous {
PQR modifiablehande; // object reference to class PQR
int culprit;
} u1;
// creating object in heap and making "modifiablehandle" point to it
u1.modifiablehandle = new PQR( );
u1.culprit = u1.culprit + 5 ; // got the point ?( pointer arithmetic
?)
Now you can modify the content of the object handle . This makes the
system vulnerable to programmatic errors. Relaibility being one of the
goals of java, prevents inclusion of features like union in the language.
If handles start pointing to random locations, several serious implications
can ensue, including dyfunctional automatic garbage collection.
By Prof. Rajesh Patkar
back