C programming on a 16-bit platform — analyze this bit-field width for validity.
#include
int main()
{
struct bits
{
int i:40; /* 40 bits requested in a 16-bit environment */
} bit;
printf("%d", (int)sizeof(bit));
return 0;
}
What is the correct diagnosis?
-
A4
-
B2
-
CError: Bit field too large
-
DError: invalid member access in structure
Answer
Correct Answer: Error: Bit field too large
Explanation
Introduction / Context:Bit-field widths cannot exceed the number of bits available in the underlying type. On a 16-bit platform, the width of int is typically 16 bits. Requesting 40 bits is not representable and must be rejected by the compiler.
Given Data / Assumptions:
- Assume int is 16 bits (typical for the stated platform).
- Member declaration uses int i:40.
Concept / Approach:For a bit-field of type int, the maximum width is the number of value bits that type can store (implementation-defined but generally the bit width of int). If the requested width exceeds that, it is ill-formed or at least a constraint violation for that target.
Step-by-Step Solution:
1) Determine int width on the target: 16 bits in this scenario.2) Compare requested width: 40 > 16, so it cannot fit.3) Compiler emits an error about an excessively large bit-field.Verification / Alternative check:Changing to unsigned int i:15; compiles. Using a wider implementation type (e.g., long) on wider platforms may also work, but not 40 bits on a 16-bit int.
Why Other Options Are Wrong:
- 2 or 4: These are guesses at sizeof and miss the primary compile-time constraint.
- Invalid member access: Access is not the issue; the declaration is.
Common Pitfalls:Assuming bit-field widths are portable across platforms; forgetting the underlying type's width limits.
Final Answer:Error: Bit field too large