What's a need for union { } in C++? [duplicate]
Possible Duplicate:
C/C++: When would anyone use a union? Is it basically a remnant from the C only days?
Hi all.
What are the reasons for unions to exist in C++? And what are they, actually?
I found this code:
#include <iostream>开发者_如何学C
using namespace std;
union mixture {
short number;
char symbol[2];
main() {
mixture m1, m2;
cout << "Enter 2 symbols to form short number made of them: ";
cin >> m1.symbol[0] >> m1.symbol[1];
cout << "2 more to go..: ";
cin >> m2.symbol[0] >> m2.symbol[1];
cout.setf(ios::hex);
cout << "Biggest received number: " << (m1.number > m2.number ? m1.number : m2.number) << endl;
system("pause");
return 0;
}
return 0;
But actually, what I win from using union { struct1, struct2 }
instead of writing struct { struct2(struct1}: a(struct1.a), b(_struct1.b {}} struct2?
to transparently support both types?
I do some embedding stuff (Arduino etc), but never seen the real usage for structs.
Examples, please.
The union lets you treat your data as either char or short without having to cast. Casting pointer between types can produce type-punning errors in the optimizer and generate incorrect output.
EDIT: For an example, I use unions to byte swap doubles and floats after reading them from a file. If you read byteswapped floating point numbers the numbers might get normalized or adjusted while bytes swapped, which of course results in junk once they're swapped:
union float_int
{
float ff;
int32_t ii;
};
float_int data;
read(fd, &data, 4); // Read 4 bytes
byteswap(data.ii); // Passing as a float can alter the bits.
float myvalue = data.ff; // My float is now byteswaped and ready to go.
A union is fundamentally different from a struct in that only one of the members is guaranteed to be usable at a time -- but this is a white lie, see next. (The data may or may not overlap depending upon the compiler, target, and various packing rules and this overlap can be [ab]used in cases The overlap can be [ab]used depending upon compiler, target, types, etc).
Conceptually a union represents a "discrete value" (X has/is A or B but X is not/does not have A and B) and it also allows the compiler (or whatever uses this model) to represent the data more efficiently in cases.
Happy coding.
In hardware level code you have to be sure your bits are in consecutive memory, this is one way to make sure of it.
edit: You dont HAVE to be sure, but there are plenty of cases it does.
Firstly, they're inherited from C and there was no good reason to remove support, so C++ retained support.
It's one of the only widely-supported ways to do type-punning (but still likely illegal by the letter of the standard).
It can save space in certain cases.
精彩评论