0
// unions.cpp
// Defines and uses a union.
// ---------------------------------------------------
#include <iostream>
using namespace std;

union WordByte
{
  private:
  unsigned short w;      // 16 bits
  unsigned char b[2];    // Two bytes: b[0], b[1]
  public:                // Word- and byte-access:
  unsigned short& word()
  { return w; }
  unsigned char& lowByte() { return b[0]; }
  unsigned char& highByte(){ return b[1]; }
};



int main()
{
   WordByte wb;
   wb.word() = 256;
   cout << "\nWord:" << (int)wb.word();
   cout << "\nLow-byte: " << (int)wb.lowByte()
       << "\nHigh-byte: " << (int)wb.highByte()
       << endl;
   return 0;
}

I hope this is not a naive question. In the above code, what is exactly this variable/object b? Moreover, how to understand unions? Could you give an example to illustrate its benefits? Any comments are greatly appreciated indeed.

kkxx
  • 571
  • 1
  • 5
  • 16
  • Have a look at https://stackoverflow.com/questions/2310483/purpose-of-unions-in-c-and-c for a general discussion of the purpose of unions – rtpax Oct 31 '19 at 15:50
  • 1
    https://en.cppreference.com/w/cpp/language/union – Jeffrey Oct 31 '19 at 15:50
  • 4
    The use case presented here is called called type punning, you use the union to access one member by means of another one. Actually, this is only legal in C, but disallowed in C++ (undefined behaviour), though, still it's used pretty often even in C++. – Aconcagua Oct 31 '19 at 15:52
  • 3
    Additionally, the code is *machine dependent* and works only on little endian machines (admitted, the very vast majority), on big endian machines (not really of relevance any more unless you unpack some old motorola processor; but some modern LE processors allow a BE mode, too!) you'd get swapped bytes back. – Aconcagua Oct 31 '19 at 15:56
  • Endian can also get you if you try to interoperate with other languages that insist on speaking big endian with others. This was the default behaviour of Java the last time I worked with it. – user4581301 Oct 31 '19 at 16:13
  • Side note: About [using namespace std](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice)... – Aconcagua Oct 31 '19 at 16:17

0 Answers0