Union layout in C: Must all members of a union have the same size, or can members differ in size with the union sized to fit the largest?

Difficulty: Easy

Correct Answer: Members can differ in size; the union is sized to accommodate the largest member (plus any alignment).

Explanation:


Introduction / Context:
Unions provide a way to store different types in the same memory location. This question clarifies whether union members must be equal in size.


Given Data / Assumptions:

  • Standard C union with multiple members of varying sizes.


Concept / Approach:
C allows union members to have any size. The union’s size is at least the size of its largest member and may include extra padding for alignment. Therefore, equality of member sizes is not required.


Step-by-Step Solution:
1) Identify largest member size among the union members. 2) Determine alignment requirements. 3) Compute union size as at least the largest member, possibly rounded for alignment. 4) Conclude members need not match sizes.


Verification / Alternative check:
Empirically check with `sizeof` on a sample union containing `char`, `int`, and `double`; member sizes differ, and union size follows the largest plus alignment.


Why Other Options Are Wrong:
Option B/D/E: No such rule in the C standard.
Option C: Power-of-two restriction does not exist.


Common Pitfalls:
Assuming union behaves like a tagged variant automatically; forgetting to track which member is active; ignoring alignment when embedding unions in structs.


Final Answer:
Members may differ; union fits the largest (with alignment).

Discussion & Comments

No comments yet. Be the first to comment!
Join Discussion