sizeof a union in C/C++

Naveen picture Naveen · Apr 11, 2009 · Viewed 64.5k times · Source

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?

Answer

mmx picture mmx · Apr 11, 2009

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.