Documente Academic
Documente Profesional
Documente Cultură
Defining a Union
Union can be defined by the keyword union.
union myUnion{
int var1;
long var2;
};
Here we have defined a union with the name myUnion and it has two members i.e. var1 of
type int and var2 of type long
union myUnion{
int var1;
long var2;
}newUnion;
So newUnion will be the variable of type myUnion. We can also declare the union as
myUnion newUnion;
union myUnion{
int var1;
long var2;
}newUnion={10.5};
or we can initialize it as
newUnion.var1= 10;
In later stages we can also initialize the var2 as well but this will over write the var1 value.
Normally when we declare the union it is allocated the memory that its biggest member can
occupy. So here in our example newUnion will occupy the memory which a long type
variable can occupy.
struct VertexStruct
{
float x,y,z;
};
VertexStruct vertexstruct;
This is what VertexStruct object will look like in memory.
vertexstruct
___________________
|
|
|
|
|
|
|
|
|_____|_____|_____|
x
y
z
So if we do
vertexstruct.x = 50;
vertexstruct.y = 10;
vertexstruct.z = 2;
We get this picture in memory:
vertexstruct
___________________
|
|
|
|
| 50 | 10 | 2 |
|_____|_____|_____|
x
y
z
This is natural and completely what youd expect.
Contrast STRUCT vs UNION
Now, CONTRAST THAT with a UNION. A UNION uses the SAME EXACT PIECE OF
MEMORY for __ALL__ of the members inside of it.
This is kind of counter-intuitive and weird.
An example:
union VertexUnion
{
float x,y,z;
};
VertexUnion vertexunion;
You get this picture in memory:
vertexunion
_______
|
|
|
|
|_____|
x
y
z
The above union effectively provides 3 ways by which to access that same single
piece of memory (x, y and z).
So if you wrote code like:
vertexunion.x = 10;
vertexunion.y = 2;
vertexunion.z = 5;
vertexunion
_______
|
|
| 5 |
|_____|
x
y
z
(Last x, y and z all refer to the same piece of memory. Since the last value assigned
there is 5, ALL OF x, y and z have the exact same value).
* Note that the sizeof( any_union ) ends up being the
sizeof( largest_member_in_union ).