-
Unions - Understanding
Hello, good morning.
My question today will be just theorical, I read the cap of the book about "Unions", now I try to figure, why do I need this? Looking close, I can do the program without an union, and also, if I don't have any indicator, I can't know what type of variable the union is holding now (at least my book wrote, that I need to put a variable inside a struct, with the union, and then always check this variable that will hold the type that the union is holding now). This is really needed? or I'm missing the best part of Union, and thinking I can change it easilly? My books seems to jump this subject fast.. he just gave 1 little loser example, and that's it.
Thank you in advance, and have a nice day :cool:
-
A common use unions for sending different messages types between threads, process, systems etc..., with the message type being stored with the message, for example:
Code:
typedef struct
{
int type;
union
{
MESSAGE01 M01 ;
MESSAGE02 M02 ;
MESSAGE03 M03 ;
};
}MESSAGE;
//A process...
void SendM02()
{
MESSAGE M;
M.type = M02_TYPE;
M.M02.A = Value1;
M.M02.B = Value2;
M.M02.C = Value3;
etc...
SendAMessge(&M);
}
//Another process...
void RecvMessage()
{
MESSAGE *M;
MESSAGE01 *M01;
MESSAGE02 *M02;
...
M = GetAMessage();
switch( M->type )
{
case M01_TYPE:
M01 = (MESSAGE01 *) &M->M01;
ValueXYZ = M01->xyz;
...
break;
case M02_TYPE:
M02 = (MESSAGE02 *) &M->M02;
Value1 = M02->A;
Value2 = M02->B;
Value3 = M02->c;
etc...
break;
case M03_TYPE:
...
break;
...
}
}
-
Also, a union is a good way to conserve memory. Unlike a struct that can hold as many variables and data types you supply and uses the maximum amount of memory of those variables added together, a union will be able to hold what you want, but only 1 at a time. A union will only hold the minumum amount of space needed to hold the maximum data type. So a union of a int and double, it will share that memory and be able to hold the max size of the double, not both. In turn, it will hold that integer in the same memory as the double.