In C bit-fields, what is printed for a 1-bit signed field initialized to 1?\n\n#include <stdio.h>\n\nint main()\n{\n struct byte {\n int one : 1;\n };\n struct byte var = { 1 };\n printf("%d\n", var.one);\n return 0;\n}\n

Difficulty: Easy

Correct Answer: -1

Explanation:


Introduction / Context:
The problem focuses on how a signed 1-bit bit-field represents values and how printing that field behaves when it is initialized with the literal value 1.


Given Data / Assumptions:

  • Field width is 1 bit and type is signed (since it is int).
  • Initializer: one = 1.
  • Output uses %d to print the value.


Concept / Approach:
A signed 1-bit quantity can represent only -1 and 0 in two’s complement. The bit pattern 1 is interpreted as -1, and the bit pattern 0 is 0. Therefore assigning 1 yields a stored representation that prints as -1 for a signed field.


Step-by-Step Solution:

Width = 1 bit; signed two’s complement range is -1..0.Store value 1 → bit pattern 1 → interpreted as -1.printf("%d", var.one) prints -1.


Verification / Alternative check:
If the field were declared unsigned (e.g., unsigned int one : 1), then printing would show 1. The signedness is the key here.


Why Other Options Are Wrong:

  • 1: Correct only for an unsigned 1-bit field.
  • 0: Would require the stored bit to be 0.
  • Compilation error: The code is valid C.


Common Pitfalls:
Forgetting that the base type of a bit-field controls signedness, and assuming that a 1 stored in a 1-bit field must print as 1 regardless of signedness.


Final Answer:
-1

More Questions from Structures, Unions, Enums

Discussion & Comments

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