Reputation: 5918
Can some give me some scenario where it is wise to use union instead of struct in some problem?
Thanks
Upvotes: 2
Views: 721
Reputation: 47952
Unions can be a way to get at the actual binary representation of a data structure.
#include <iostream>
#include <iomanip>
union MyUnion {
int integer;
unsigned char bytes[sizeof(int)];
};
int main() {
MyUnion foo;
foo.integer = 42;
std::cout << "My computer represents " << foo.integer << " as:";
for (int i = 0; i < sizeof(foo.bytes); ++i) {
std::cout << ' ' << std::hex << std::setw(2) << std::setfill('0')
<< static_cast<unsigned int>(foo.bytes[i]);
}
std::cout << std::endl;
return 0;
}
There are other ways to accomplish this in C++, but using a union makes the intent rather transparent.
Note that the results may vary by platform (little-endian vs. big-endian) and possibly by compiler (how it packs and pads arrays and data types). Most of the time, you shouldn't need to do stuff like this.
Sometimes you have to deal with a legacy binary format with several different interpretations. ("If the first byte is a 3, then the next value is a zero-terminated ASCII string of at most 16 bytes, otherwise, the next DWORD-aligned int is an offset in the resource block ..."). If you understand all the endianness and packing issues involved, a union makes it relatively easy to tease apart such a struct.
Upvotes: 0
Reputation: 5262
It is wise to use a union whenever you have a data bottleneck, and you have two pieces of data that are mutually exclusive, but available in the same data structure.
Let's say I have two messages that have identical data, except for two pieces of data are mutually exclusive between them, and are close in size (an 32 bit int, and a 4 byte array). I can make a union of the two, and the messages can share data structure without having an increase in size that they won't use.
Be aware of problems:
The data may not be mutually exclusive in the future. Initialization of the mutually exclusive data. Reusing the same instance of the data for both messages (you'll need to be sure you switch out the mutually exclusive data, or the receiver deals with junk data).
Having a union to refer to the same data with different type definitions is undefined behavior. So:
Also, Do not use a union with data that is a pointer which can be deleted from another point in the code. You likely have a deleted pointer in your union and accidentally refer to the data using the other definition.
And most importantly, if you do not understand this answer. Do not use a union.
Upvotes: 4