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?

  1. A1
  2. B7
  3. 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.
Practice this topic Back to topic

Books on C Programming Basics Ad

As an Amazon Associate I earn from qualifying purchases.

More C Programming Basics questions

  1. Which of the following is the output when the code above, which uses the macro SQUARE defined with #define, is executed?
  2. The header file sensor.h is written as above. Which of the following is the purpose of the three lines #ifndef, #define and #endif?
  3. Which of the following is the output when the code above is written inside the main function and executed?
  4. A microcontroller output register is declared and used as above. Which of the following correctly describes this declaration?
  5. Which of the following describes undefined behavior as defined by the C standard?