C programming — identify the compile-time issue in this bit-field struct definition and sizeof usage.\n\n#include<stdio.h>\n\nint main()\n{\n struct a\n {\n float category:5; /* bit-field on float /\n char scheme:4; / small bit-field on char (non-standard extension) */\n };\n printf("size=%d", (int)sizeof(struct a));\n return 0;\n}\n\nWhat is the correct diagnosis?

Difficulty: Easy

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

More Questions from Structures, Unions, Enums

Discussion & Comments

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