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>
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.