Unions are special because they overlay their members in memory - the size and alignment of a union is determined by its largest member. Let's explore this with examples:
Here’s a code example using a basic union:
#include <iostream>
union SimpleUnion {
char C;// 1 byte
int I;// 4 bytes
double D;// 8 bytes
};
int main() {
std::cout << "Union size: "
<< sizeof(SimpleUnion)
<< " bytes\n"
<< "Union alignment: "
<< alignof(SimpleUnion)
<< " bytes\n"
<< "Individual alignments:\n"
<< " char: " << alignof(char) << " bytes\n"
<< " int: " << alignof(int) << " bytes\n"
<< " double: " << alignof(double)
<< " bytes\n";
SimpleUnion U;
U.D = 3.14;
std::cout << "Address of U: "
<< static_cast<void*>(&U) << "\n"
<< "Address of U.C: "
<< static_cast<void*>(&U.C) << "\n"
<< "Address of U.I: "
<< static_cast<void*>(&U.I) << "\n"
<< "Address of U.D: "
<< static_cast<void*>(&U.D) << "\n";
}
Union size: 8 bytes
Union alignment: 8 bytes
Individual alignments:
char: 1 bytes
int: 4 bytes
double: 8 bytes
Address of U: 000000CF4974F8B8
Address of U.C: 000000CF4974F8B8
Address of U.I: 000000CF4974F8B8
Address of U.D: 000000CF4974F8B8
In this example, we use a union that includes a user-defined type:
#include <iostream>
struct AlignedStruct {
double Value;// 8 bytes
char Tag;// 1 byte + padding
};
union ComplexUnion {
char Simple;// 1 byte
AlignedStruct Complex;// Determines union size
};
int main() {
std::cout << "Struct size: "
<< sizeof(AlignedStruct) << " bytes\n"
<< "Union size: "
<< sizeof(ComplexUnion) << " bytes\n"
<< "Union alignment: "
<< alignof(ComplexUnion) << " bytes\n";
}
Struct size: 16 bytes
Union size: 16 bytes
Union alignment: 8 bytes
Important points about union alignment:
Answers to questions are automatically generated and may not have been reviewed.
Learn how memory alignment affects data serialization and how to handle it safely