In C, is the size of a union always exactly equal to the size of its longest (largest) member, or can alignment/padding make the union larger?
-
ANot always equal; it is at least the size of the largest member and may be larger due to alignment.
-
BAlways exactly equal to the largest member with no exceptions.
-
CAlways the sum of all member sizes.
-
DSmaller than the largest member if bit-fields are present.
-
EDepends only on compiler optimization level, not alignment.
Answer
Correct Answer: Not always equal; it is at least the size of the largest member and may be larger due to alignment.
Explanation
Introduction / Context: Unions overlay their members at the same memory location. This question probes understanding of how a union’s size is determined by the largest member and how alignment constraints may add padding, affecting the final size.
Given Data / Assumptions:
- Standard C implementation with typical alignment rules.
- Union has members of possibly different sizes and alignment requirements.
Concept / Approach: The C standard permits implementations to add padding so that any member can be accessed with proper alignment. Therefore, union size must be at least the size of its largest member, but may be rounded up to satisfy the strictest alignment requirement among its members.
Step-by-Step Solution: 1) Identify the largest member size among all union members. 2) Determine the strictest alignment required by any member. 3) Compute the union size as a value not less than the largest member and possibly rounded up to the alignment boundary. 4) Conclude that equality is common but not guaranteed; alignment can increase size.
Verification / Alternative check: On many systems, `sizeof(union)` equals `max(sizeof(member_i))`. On others, `sizeof(union)` may be larger to ensure that placing the union inside arrays or structs keeps members aligned.
Why Other Options Are Wrong: Option B: Ignores alignment; not guaranteed. Option C: Unions do not sum sizes; that is for structs (and even then with padding). Option D: Bit-fields do not make a union smaller than its largest member. Option E: Optimization level does not change language alignment rules.
Common Pitfalls: Assuming equality across all platforms; ignoring alignment when laying out data; relying on a specific `sizeof` in portable code.
Final Answer: At least the largest member; may be larger due to alignment.