Difficulty: Medium
Correct Answer: No, you cannot have an array of plain bit-fields; use an array of structs that contain bit-fields.
Explanation:
Introduction / Context: Bit-fields in C are a special way to pack named fields into an integer type inside a struct. This question checks whether a programmer can declare an array whose elements are bit-fields themselves, or whether bit-fields are only valid as members inside a struct. Understanding how bit-fields are defined and stored is essential for writing portable, correct C code.
Given Data / Assumptions:
Concept / Approach: In C, a bit-field is not a type on its own; it is a declarator that modifies a struct member. Therefore, bit-fields must be declared as members of a struct (or union). Arrays require an element type, but a bit-field does not constitute a standalone type, so an array of raw bit-fields is ill-formed. The correct approach is to put the bit-field inside a struct and then make an array of that struct.
Step-by-Step Solution: 1) Recognize that `unsigned int:3` is not a type; it is a field width applied to a struct member. 2) Arrays require a complete element type such as int, char, or a struct type. 3) Because a bit-field is not a complete type, `unsigned int:3 arr[10];` is invalid. 4) Correct pattern: define a struct with a bit-field member, then declare an array of that struct. Example: `struct Flags { unsigned int f:3; }; struct Flags arr[10];`
Verification / Alternative check: Try compiling `unsigned int:3 arr[10];`—a conforming compiler issues an error because the element lacks a proper type. The struct-array version compiles and works across compilers.
Why Other Options Are Wrong: Option B: Suggests raw bit-field arrays; this is not allowed since a bit-field is not a standalone type. Option C: Width 1 does not change the rule; still not a type. Option D: C++ also requires bit-fields to be members; raw bit-field arrays are not valid there either. Option E: CHAR_BIT size is unrelated; portability does not make the construct valid.
Common Pitfalls: Confusing a bit-field declaration with a type; assuming any bit width makes it a type; relying on non-portable extensions.
Final Answer: No: declare a struct with bit-fields and make an array of that struct.
Discussion & Comments