2

Any thoughts on why I would get two different results, I suspect it has to do with a signed integer, but can't see the difference.

#include <stdio.h>

int main() {
    int x = 32;
    printf("%x\n", (~0 << x));
    printf("%x\n", (~0 << 32));
    return 0;
}

OUTPUT:

ffffffff
0

IrAM
  • 1,720
  • 5
  • 18
Michael
  • 87
  • 8
  • 2
    Looks like you've invoked undefined behavior: https://stackoverflow.com/questions/3784996/why-does-left-shift-operation-invoke-undefined-behaviour-when-the-left-side-oper – Jeremy Friesner Feb 10 '21 at 05:01
  • 1
    @JeremyFriesner: It's also UB for another reason, since it shifts an int by an amount greater than or equal to its width. That's probably the immediate cause of this behavior: the runtime left-shift instruction masks the shift count, but the compile-time constant folding doesn't. https://stackoverflow.com/questions/11270492/what-does-the-c-standard-say-about-bitshifting-more-bits-than-the-width-of-type?noredirect=1&lq=1 – Nate Eldredge Feb 10 '21 at 05:18
  • Don't you get some warning from your compiler? If not, turn up warning level. For GCC you can do this with `-Wall -Wextra` – Gerhardh Feb 10 '21 at 10:35

0 Answers0