Consider the following piece of code:
// Simply loop over until 64 is hit.
unsigned long x = 0;
for (int i = 0; i <= 64; i++) {
if (i == 64) {
x = 1ul << i;
printf("x: %d\n", x);
}
}
We know that unsigned long is 64-bit wide, and left shifting 1 by 64 positions would become 1000...000 (64 zeros behind one), and would have been truncated to 0. However, the actual printout gives:
x: 1
The strange thing is, if we just do
printf("x: %d\n", (1ul << 64));
It would print 0.
Can anyone explain why this is happening? Why in the first case, the program mistakenly produces 1 instead of 0, but in the second case it's correct?