LearnFrenzy
Sign in Take a free test

Bitwise Operators · Find the Error · Question 2

1 << 31 with a signed int Answer, explanation & discussion

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

The program below has a bug. Which statement correctly describes it?

main.c
#include <stdio.h>

int main(void) {
    int bit = 31;
    int mask = 1 << bit;
    printf("%d\n", mask != 0);
    return 0;
}
  • A bit must be unsigned
  • B 1 is a signed int, and 1 << 31 does not fit in a 32-bit int – undefined behaviour; write 1u << 31 Correct
  • C mask != 0 is always false
  • D There is no bug
Correct Answer: Option B

The literal 1 is an int. Shifting it into the sign bit produces a value that int cannot represent, which is undefined. 1u << 31 is a well-defined unsigned 0x80000000.

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