0

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.

Community
  • 1
  • 1
kagali-san
  • 2,964
  • 7
  • 48
  • 87
  • 4
    You win space. A union is only the size of its biggest member (+/- alignment). – Xeo Apr 01 '11 at 19:52
  • the web will tell you [what they are](http://en.wikipedia.org/wiki/Union_(computer_science)) – David Heffernan Apr 01 '11 at 19:53
  • 3
    Same as [C/C++: When would anyone use a union? Is it basically a remnant from the C only days?](http://stackoverflow.com/questions/4788965/c-c-when-would-anyone-use-a-union-is-it-basically-a-remnant-from-the-c-only-d). – Matthew Flaschen Apr 01 '11 at 19:53
  • @David Heffernan, no real-world examples where. Who needs them? P.S. http://google.com/codesearch?hl=en&lr=&q=%22union+%7B%22++lang%3Ac%2B%2B&sbtn=Search had more chances to become an answer. – kagali-san Apr 01 '11 at 20:03

4 Answers4

2

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.

2

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.
John Gordon
  • 2,576
  • 3
  • 24
  • 29
1

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.

Jake Kalstad
  • 2,045
  • 14
  • 20
1

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.

Mark B
  • 95,107
  • 10
  • 109
  • 188