Unions provide different views of looking at the same memory location.
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 . I don't
think James Gosling can tolerate this . So you got the point.
By Prof. Rajesh Patkar
back