Quantcast
Channel: Visual C++ Tips
Viewing all articles
Browse latest Browse all 10

C++ Union – Is it still Relevant?

$
0
0

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?


Viewing all articles
Browse latest Browse all 10

Trending Articles