Why this code does not write 0 as a last element but 18446744073709551615? (compiled with g++)
#include <iostream>
using namespace std;
int main(){
unsigned long long x = (unsigned long long) (-1);
for(int i=0; i <= 64; i++)
cout << i << " " << (x >> i) << endl;
cout << (x >> 64) << endl;
return 0;
}
You overflow the shift. If you've noticed, GCC even warns you:
How come? You include 64 as a valid shift, which is an undefined behavior. counting from 0 to 64 there are 65 numbers (0 included). 0 being the first bit (much like arrays).
Will produce the output you'd expect.
This warning from the compiler should be a hint:
"warning: right shift count >= width of type"
This results in undefined behavior:
http://sourcefrog.net/weblog/software/languages/C/bitshift.html
I get:
so perhaps it's undefined behavior?