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.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…