Originally Posted by
vermarajeev
Also I was just wondering under what situations we should use a structure and when we should use a union?
A union is a set of "memory sharing variables". In example
union myUnion
{
int iValue;
float fValue;
};
struct myStruct
{
int iValue;
float fValue;
};
myStruct myS;
myS.iValue = 1;
myS.fValue = 2.0;
myUnion myU;
myU.iValue = 1;
myU.fValue = 2.0;
cout << myS.iValue << " " << myS.fValue << endl;
cout << myU.iValue << " " << myU.fValue << endl;
union myUnion
{
int iValue;
float fValue;
};
struct myStruct
{
int iValue;
float fValue;
};
myStruct myS;
myS.iValue = 1;
myS.fValue = 2.0;
myUnion myU;
myU.iValue = 1;
myU.fValue = 2.0;
cout << myS.iValue << " " << myS.fValue << endl;
cout << myU.iValue << " " << myU.fValue << endl;
To copy to clipboard, switch view to plain text mode
print something like
1 2.0
<some_value> 2.0
1 2.0
<some_value> 2.0
To copy to clipboard, switch view to plain text mode
this because when you assign value to myU.fValue you set memory area use by myU.iValue
Union are useful to share the same memory area amoung several variables.
In Example this function
void printSwappedByte(unsigned short _val)
{
union
{
unsigned short sV;
unsigned char cV[2];
};
sV = _val;
cout << (unsigned int) cV[1] << " " << (unsigned int) cV[0] << endl;
}
void printSwappedByte(unsigned short _val)
{
union
{
unsigned short sV;
unsigned char cV[2];
};
sV = _val;
cout << (unsigned int) cV[1] << " " << (unsigned int) cV[0] << endl;
}
To copy to clipboard, switch view to plain text mode
print val bytes in revers order;
Bookmarks