C programming — identify the compile-time issue in this bit-field struct definition and sizeof usage.
#include
int main()
{
struct a
{
float category:5; /* bit-field on float /
char scheme:4; / small bit-field on char (non-standard extension) */
};
printf("size=%d", (int)sizeof(struct a));
return 0;
}
What is the correct diagnosis?
-
AError: invalid structure member in printf
-
BError in this float category:5; statement
-
CNo error
-
DError: sizeof on incomplete type
Answer
Correct Answer: Error in this float category:5; statement
Explanation
Introduction / Context:This item again tests the rule that bit-fields must be of integer type or _Bool. A float bit-field violates the language requirements in standard C.
Given Data / Assumptions:
- struct a declares float category:5; and char scheme:4;
- Program prints sizeof(struct a).
Concept / Approach:Bit-fields of floating types are not permitted. Some compilers may also restrict the underlying integer types for bit-fields; _Bool, signed int, and unsigned int are the portable choices. Therefore the error is specifically the float bit-field line, not the sizeof or printf call.
Step-by-Step Solution:
1) Inspect member types: float for a bit-field violates the rule.2) Compilation fails before evaluating sizeof.3) If changed to unsigned int category:5;, the program compiles and sizeof can be printed.Verification / Alternative check:Replace float with unsigned int; compile succeeds confirming the diagnosis.
Why Other Options Are Wrong:
- Invalid structure member in printf: printf is fine; it prints an int cast of sizeof.
- No error: Contradicted by the rule on bit-field types.
- sizeof on incomplete type: struct a is complete at the point of sizeof.
Common Pitfalls:Assuming any type can be a bit-field, or blaming printf instead of the declaration.
Final Answer:Error in this float category:5; statement