In C programming, can we directly declare an array whose elements are bit-fields, or must bit-fields be members of a struct only? Explain the correct approach with a short note on why arrays of plain bit-fields are not allowed.
-
ANo, you cannot have an array of plain bit-fields; use an array of structs that contain bit-fields.
-
BYes, you can declare int:3 arr[10]; and index it normally.
-
CYes, but only if the bit-field width is 1.
-
DOnly in C++, not in C.
-
EOnly on systems where CHAR_BIT is 8.
Answer
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:
- C language, not C++.
- Standard bit-field syntax like unsigned int x:3; used only inside a struct.
- Need to decide if arr[i] can be declared directly as a bit-field element.
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.