In the following code, can the value of int be predicted ( how ? ), or it is just the garbage ?
union a
{
int i;
char ch[2];
};
a u;
u.ch[0] = 0;
u.ch[1] = 0;
cout<<u.i;
}
In the following code, can the value of int be predicted ( how ? ), or it is just the garbage ?
union a
{
int i;
char ch[2];
};
a u;
u.ch[0] = 0;
u.ch[1] = 0;
cout<<u.i;
}
I would say that depends on the size of int
and char
. A union
contains the memory of the largest variable. If int
is 4 bytes and char[2]
represents 2 bytes, the int
consumes more memory than the char
-array, so you are not initialising the full int
-memory to 0 by setting all char
-variables. It depends on your memory initialization mechanisms but basically the value of the int
will appear to be random as the extra 2 bytes are filled with unspecified values.
Besides, filling one variable of a union
and reading another is exactly what makes unions unsafe in my oppinion.
If you are sure that int
is the largest datatype, you can initialize the whole union
by writing
union a
{
int i;
char ch[2];
};
void foo()
{
a u = { 0 }; // Initializes the first field in the union
cout << u.i;
}
Therefore it may be a good idea to place the largest type at the beginning of the union. Althugh that doesn't garantuee that all datatypes can be considered zero or empty when all bits are set to 0.