What is printed by this C code: struct { unsigned f : 2; } s; s.f = 7; printf(“%u”, s.f);?
Correct answer D. 3
Explanation
f is an unsigned bit-field 2 bits wide, so it can hold only 0 to 3. Assigning 7 (binary 111) to an unsigned type reduces the value modulo 4, keeping the low two bits, 11, which is 3. This wrap-around is well defined for unsigned bit-fields, though compilers warn that the value changes. Bit-fields save space in flags and hardware register layouts.
Answer checked How we write and check questions
Discussion