In C programming, can a union contain members of different sizes, and what does that imply for its overall size allocation?

Difficulty: Easy

Correct Answer: Correct — union members may have different sizes; the union's size equals the size of its largest member

Explanation:


Introduction / Context:
Unions in C allow multiple members to share the same memory location. This question checks whether union members may have different sizes and what that means for storage and alignment.


Given Data / Assumptions:

  • Standard C (C11/C17 rules apply).
  • Union has two or more members of potentially different types.
  • Typical platform alignment rules apply.


Concept / Approach:
The size of a union is at least the size of its largest member, possibly rounded up for alignment. All members overlap at offset 0, so only one member is meaningfully stored at a time.


Step-by-Step Solution:
1) Consider a union with int and double members.2) sizeof(int) might be 4; sizeof(double) might be 8.3) sizeof(union) becomes at least 8 (the larger member), not 4 + 8.4) Different member sizes are allowed; the union allocates memory to accommodate the largest.


Verification / Alternative check:
Check sizeof for several unions on your platform; it always matches the largest member (with alignment considered).


Why Other Options Are Wrong:
Option B: Claims equal sizes are required — not true in C.
Option C: Not implementation freedom; the standard allows differing sizes.
Option D: No packing pragmas are required for this rule.
Option E: Same alignment is not a prerequisite for differing sizes.


Common Pitfalls:
Assuming unions sum member sizes; they do not. Confusing unions with structs regarding layout and storage is common.


Final Answer:
Correct — union members may have different sizes; the union's size equals that of its largest member.

Discussion & Comments

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