#include <iostream>
using namespace std;
struct Data {
int i;
char c;
double d;
};
int main() {
Data data = {10, 'A', 3.14};
cout << sizeof(data) << " ";
cout << data.i << " " << data.c << " " << data.d << endl;
return 0;
}The structure has padding bytes to align members properly. Typically, the size is 24 bytes on a 64-bit system. The values printed are exactly those initialized.
#include <iostream>
using namespace std;
union Data {
int i;
char c;
double d;
};
int main() {
Data data;
data.i = 10;
data.c = 'A';
cout << data.i << " " << data.c << endl;
return 0;
}Assigning to data.c overwrites the first byte of data.i. The ASCII value of 'A' is 65, so data.i now starts with 65 in its lowest byte, resulting in 65 when printed as int.
Structures allocate memory for each member separately, so total size is sum plus padding. Unions allocate memory only once, equal to the size of the largest member, since all members share the same memory space.
#include <iostream>
using namespace std;
union Data {
int i;
float f;
};
int main() {
Data data;
data.i = 1065353216; // bit pattern for float 1.0
cout << data.f << endl;
return 0;
}The integer 1065353216 has the same bit pattern as the float 1.0 in IEEE 754 format. Accessing the float member after setting the int member shows 1.0.
Unions save memory by sharing the same memory space for different members, which is useful when only one member is used at a time. Structures allocate separate memory for each member, which uses more memory.