LearnFrenzy
Sign in Take a free test

Bitwise Operators · Find the Error · Question 5

Bug: ! used instead of ~ to clear a bit Answer, explanation & discussion

  • Find the error
  • Medium
  • 0 comments
  • Answer explained
  • Moderated community
Question 5 Back to Exercise

The aim is to clear bit 2 of flags (0b1111). What does the program print, and why?

main.c
#include <stdio.h>

int main(void) {
    unsigned flags = 15;
    flags &= !(1u << 2);
    printf("%u\n", flags);
    return 0;
}
  • A 0 – !(4) is 0, so the AND clears every bit; it should be ~(1u << 2) Correct
  • B 11 – bit 2 was cleared
  • C 15 – nothing changed
  • D It does not compile
Correct Answer: Option A

! is logical NOT: any non-zero value becomes 0. AND-ing with 0 wipes all bits. The bitwise NOT ~(1u << 2) gives …11111011, which clears only bit 2 and leaves 11. Compilers even warn that !(1u << 2) is a constant.

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.

Search LearnFrenzy

Esc

Quick links