I am currently experimenting with bitwise operations in C and I am trying to understand why this code prints a different value for variable a
and variable b
.
I know that a 32 bit shift overflows the 1 variable (that is a normal int), but my understanding is that it should print 0 in both cases.
Instead, it prints what seems like a random number with the unsigned int a
and a 0 value with the unsigned long int b
.
#include <stdio.h>
int main(){
printf("%lu %lu\n",sizeof(int), sizeof(long int));
unsigned int a = 1 << 32;
unsigned long int b = 1 << 32;
printf("%u %lu\n", a, b);
return 0;
}
Sample output:
4 8
374588997 0
What am I missing?
EDIT
Now I am trying only with a 31 bit shift, the compiler gives me NO warning. Source:
#include <stdio.h>
int main(){
int shift = 31;
unsigned long int b = 1 << shift;
printf("%lu\n", b);
return 0;
}
And it outputs 18446744071562067968
, that is really not 2^31. Any clue?