In C, can bit-fields be declared inside a union?

Difficulty: Easy

Correct Answer: Correct — C forbids bit-fields inside unions; use structs for bit-fields

Explanation:


Introduction / Context:
Bit-fields compactly represent flags or small integers within a structure. This question checks whether bit-fields are legal inside unions.


Given Data / Assumptions:

  • We are in standard C.
  • Bit-field syntax uses a colon with a width in a struct declaration.


Concept / Approach:
C permits bit-fields only in structures, not in unions. Bit-fields describe allocation within a single struct member record; unions overlay members and therefore do not support bit-field declarations.


Step-by-Step Solution:
1) Declare struct with unsigned flags: unsigned a:1; unsigned b:3; — valid.2) Attempt to place the same declarations directly in a union — this is not allowed by the language rules.3) Therefore, use a struct (possibly nested inside a union) if bit-fields are required.


Verification / Alternative check:
Try compiling a union containing bit-field syntax; conforming compilers will reject it or issue diagnostics.


Why Other Options Are Wrong:
Option B: Asserts the opposite of the standard rule.
Option C/D/E: Add conditions that the standard does not define; they remain disallowed.


Common Pitfalls:
Confusing what can be placed in unions versus structs. A typical workaround is a union that contains a struct-with-bitfields as one alternative member.


Final Answer:
Correct — C forbids bit-fields inside unions; use structs for bit-fields.

More Questions from Structures, Unions, Enums

Discussion & Comments

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