C Programming Basics
struct { unsigned int x : 3; } s;
int v = 9;
s.x = v;
printf("%d\n", s.x);Which of the following is the output when the code above, which stores 9 in a 3-bit bit-field, is executed?
- A1
- B7
- C9
Show answer and explanation
Answer: A. 1
x is a 3-bit unsigned bit-field, so it can only represent 0 to 7. Storing a value that does not fit in an unsigned type gives the remainder modulo 2³ = 8, so 9 becomes 1. Bit-fields can be used to pack small values such as register setting fields or communication flags, but details such as the bit order of the fields differ between implementations. With gcc, assigning the constant 9 directly to s.x gives a warning.
- A. Correct. 9 modulo 8 is 1.
- B. This is the value obtained by assuming it stops (saturates) at the maximum 7.
- C. A 3-bit field cannot hold 9, and the upper bits are lost.