Pranjal Misra Pranjal Misra - 4 years ago 93
C++ Question

Can someone explain how the union works in this line of code and how the numbers are being swaped?

#include<iostream>
using namespace std;
union swap_byte { //This code is for union
public:
void swap();
void show_byte();
void set_byte(unsigned short x);
unsigned char c[2];
unsigned short s;
};

void swap_byte::swap() //swaping the declared char c[2]
{
unsigned char t;
t = c[1];
c[1] = c[0];
c[0] = t;
}
void swap_byte::show_byte()
{
cout << s << "\n";
}
void swap_byte::set_byte(unsigned short x) //input for the byte
{
s = x;
}
int main()
{
swap_byte b;
b.set_byte(49034);
b.show_byte();
b.swap();
b.show_byte();
cin.get();
return 0;
}


I am unable to understand the purpose of union and I saw the implemetation of union via above code but got confused please explain what the code does and how the union is working.

Answer Source

An union is a special kind of struct in which members overlap, so the layout of swap_byte is something like:

|     |     | char c[2]
-------------
|           | short s

But this occurs in the same 2 memory bytes. That's why swapping the single bytes of c produces the effect of swapping the most relevant and least relevant byte of the short number.

Mind that this can be fragile and it's not the best way to do it because you must make sure of multiple aspects. In addition, by default, accessing an union field different from the last one set yields undefined behavior in C++ (while it's allowed in C). This is an old trick which is rarely needed.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download