What is the sizeof the union in C/C++? Is it the sizeof the largest datatype inside it? If so, how does the compiler calculate how to move the stack pointer if one of the smaller datatype of the union is active?
A union
always takes up as much space as the largest member. It doesn't matter what is currently in use.
union {
short x;
int y;
long long z;
}
An instance of the above union
will always take at least a long long
for storage.
Side note: As noted by Stefano, the actual space any type (union
, struct
, class
) will take does depend on other issues such as alignment by the compiler. I didn't go through this for simplicity as I just wanted to tell that a union takes the biggest item into account. It's important to know that the actual size does depend on alignment.