Question 4
Back to Exercise
The user has only READ permission (flags == 0x1). What does this program print, and why?
#include <stdio.h>
#define READ 0x1u
#define WRITE 0x2u
int main(void) {
unsigned flags = READ;
puts((flags && WRITE) ? "can write" : "read-only");
return 0;
}
- A read-only – the test is correct
- B can write – && only checks that both sides are non-zero; it should be (flags & WRITE) Correct
- C Nothing – it does not compile
- D can write – because READ and WRITE overlap
Correct Answer: Option B
flags && WRITE is "flags is non-zero and WRITE is non-zero", which is true. The bit test needs the bitwise AND: (flags & WRITE) != 0. Compilers warn about && with a constant operand.
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!