Software & Finance





C Programming (Turb C++ Compiler) - Struct and Union





All the members in union will share the same memory location unlike struct.
We have a same set of members for MyStruct and MyUnion in the example below. Compiler will allocate 16 bytes for the given structure and allocate just 4 bytes for the union.

struct MyStruct

{

long lValue;

char ch;

char buf[4];

float f;

};

 

union MyUnion

{

long lValue;

char ch;

char buf[4];

float f;

};


Another typical example in COM is VARIANT. The following is VARIANT definition from OAIDL.H from Visual C++ SDK Library. It can accommodate any kind of data type using VARTYPE and its corresponding variable in the union member.

You can refer to the VARIANT struct definition at http://msdn.microsoft.com/en-us/library/ms221627(VS.80).aspx

The sizeof(VARIANT) is just 16 bytes.