Question 1
Back to Exercise
The program below has a bug. Which statement correctly describes it?
#include <stdio.h>
unsigned low_mask(int bits) { /* mask with the lowest `bits` bits set */
return (1u << bits) - 1;
}
int main(void) {
printf("%u\n", low_mask(8));
printf("%u\n", low_mask(32));
return 0;
}
- A low_mask(8) is wrong
- B For bits == 32, 1u << 32 shifts by the full width of unsigned – undefined behaviour Correct
- C The function must return int
- D There is no bug; it prints 255 and 4294967295
Correct Answer: Option B
A shift count must be less than the width of the type. Handle 32 separately: return bits >= 32 ? UINT_MAX : (1u << bits) - 1;. On x86 the unchecked version usually returns 0, not the mask you wanted.
Discussion & Comments 0
Share your method, a shortcut, or ask about a step you didn't follow.
No comments yet. Be the first to share your solution!