LearnFrenzy
Sign in Take a free test

Bitwise Operators · Find the Error · Question 4

Bug: && used instead of & to test a flag Answer, explanation & discussion

  • Find the error
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 4 Back to Exercise

The user has only READ permission (flags == 0x1). What does this program print, and why?

main.c
#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!

Post your comment

Comments appear after a quick review by our team.

Popular