1

I am currently practicing bitshifting in order to test my knowledge and cement my abilities in C, though I am currently running into a bug with C. This code represents my problem:

#include <stdio.h>

int main() {
    int p = 32;

    printf("%d", ~0 << 32);
    printf("%d", ~0 << p);

    return 0;
}

~0 << 32 is 0 (all zero bits), ~0 << p is -1 (all 1 bits). Why does C interpret these statements differently?

Jacob Denson
  • 391
  • 1
  • 4
  • 14

1 Answers1

2

Because the literal 0 is of type int. When you perform ~0 you end up with a negative int. Left-shifting a negative int is undefined behavior. And left shifting past the width of an integer is also undefined behavior.

So the expected result is: anything.

Why a particular case of undefined behavior causes a certain thing to happen is nothing to dwell on or try to understand. You wrote some bugs and then the program stopped behaving in a predictable manner, simple as that.

Lundin
  • 195,001
  • 40
  • 254
  • 396