C programming — identify the compile-time issue in this bit-field example.\n\n#include<stdio.h>\n\nint main()\n{\n struct bits\n {\n /* Attempting a bit-field on a floating type */\n float f:2;\n } bit;\n\n printf("%d", (int)sizeof(bit));\n return 0;\n}\n\nWhich option best describes the problem (if any)?

Difficulty: Easy

Correct Answer: Error: cannot set bit field for float

Explanation:


Introduction / Context:
C bit-fields allow packing of integer data into specific numbers of bits inside a struct. The key restriction is that bit-fields must use integer types or _Bool, not floating types. This question tests recognition of that rule and the kind of error a compiler must emit.


Given Data / Assumptions:

  • A struct contains a member declared as float f:2.
  • Program attempts to print sizeof(bit).
  • We assume a standards-conforming C compiler.


Concept / Approach:
The C standard permits bit-fields with types _Bool, signed int, or unsigned int (and implementation-defined integer types). Floating-point types (float, double, long double) are not permitted for bit-fields.


Step-by-Step Solution:

1) Inspect declaration: float f:2; — type is float, width is 2 bits.2) By rule, float cannot be a bit-field base type.3) Therefore the program fails to compile; sizeof(bit) is never reached.


Verification / Alternative check:
Changing the member to unsigned int f:2; or _Bool f:1; compiles and works, confirming the issue is the float bit-field, not sizeof or printf.


Why Other Options Are Wrong:

  • No error: Incorrect because the compiler must reject a float bit-field.
  • Undefined behavior: The program does not reach runtime; it is a compile-time error.
  • printf mismatch: The cast to int in the fixed version or using %zu for size_t would be separate; the core error is earlier.


Common Pitfalls:
Assuming any type can be used in a bit-field or confusing compiler extensions with standard C rules.


Final Answer:
Error: cannot set bit field for float

More Questions from Structures, Unions, Enums

Discussion & Comments

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