sizeof a union in C/C++

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.

Leave a Comment