C++ Union – Is it still Relevant?
Do you remember the old days, where memory was a premium? At that time, unions were used to save memory by merging multiple variables. Gone are the days where we had memory constraints. Now we have GB’s of RAM itself. So are unions just overhead to language now? Or is it still useful?

![]()
The merging property of unions can be used for parsing values. For instance have a look at the MessageParser below. If you want to deal with byte streams with specific message format, then unions will be really helpful.
#pragma pack(1)
// Message layout.
struct MessageLayout
{
char Signature[3];
WORD HeaderLen;
WORD Param1;
BYTE Param2;
};
// Union to parse header from byte streams.
union MessageHeaderParser
{
// Byte stream.
BYTE Bytes[8];
MessageLayout Layout;
};
int _tmain(int argc, _TCHAR* argv[])
{
// DWORD Parser.
BYTE Bytes[] = { 'M','Z', 0, // Header Signature.
10,0, // Header Length
20,0, // WORD param
30 }; // BYTE Param.
MessageHeaderParser Parser;
memcpy(&Parser.Bytes, Bytes, 8);
// Get the HIWORD by using standard windows macro.
cout << "Signature :" << Parser.Layout.Signature << endl;
cout << "Msg Length :" << Parser.Layout.HeaderLen << endl;
cout << "WORD param :" << Parser.Layout.Param1 << endl;
cout << "BYTE param :" << (int)Parser.Layout.Param2 << endl;
_getch();
return 0;
}
Download the code from here.
BTW, Do you know that the famous Audi brand is a union of 4 old legendary car companies? The four rings represents each of the four companies. Interesting, the history is. isn’t it?
You know the problem with your code? It is undefined behavior and that is not what unions are intended for. Only one field in a union can be active at any one time, so at the point you index Layout anything can happen.
Hi Liam,
I’m afraid that I’ve to disagree. The property of union is that its size will be the max size of its biggest member variable. So, you can access any variable of a union at any time. There won’t be any instability.
Provided one thing, if you initialize the smallest value and try to access bigger member, ofcourse it will be garbage. The point is if you use it wisely, you can take advantage of its memory merging property for things like parsing etc.
Best Regards,
Jijo.