Compare Union and Struct Storage
Compare two storage layouts
A struct keeps both its fields at once. A union uses shared space for alternatives. The exact sizes depend on the implementation's type sizes and alignment, so don't expect a particular byte count. The union needs enough space for either field; the struct needs separate space for both.
Alignment is a type's requirement for where an object may begin in memory. A compiler may insert unused padding bytes between struct members or at the end to meet these requirements. A union may also have end padding. Its size is at least the size of its largest member, not necessarily exactly that size. The following comparisons avoid assuming a byte count.
#include <stdio.h>
struct Separate {
int count;
double weight;
};
union Shared {
int count;
double weight;
};
int main(void) {
printf("Union fits int: %d\n", sizeof(union Shared) >= sizeof(int));
printf("Union fits double: %d\n", sizeof(union Shared) >= sizeof(double));
printf("Struct has both fields: %d\n", sizeof(struct Separate) >= sizeof(int) + sizeof(double));
return 0;
}
Each comparison prints 1 on a conforming C implementation. The sizes help illustrate the different layouts, but you choose a union or struct based on whether the values must be available at the same time.