I have some code like this:
int foo(unsigned long long x) {
unsigned int x1 = (unsigned int)(x >> 32);
unsigned int x2 = (unsigned int)(x);
if (x == 0) {
cout << x1 << " " << __builtin_clz(x1) << endl;
cout << x2 << " " << __biultin_clz(x2) << endl;
}
}
The output on x = 0
is:
0 587581823
0 -32
And the most strange thing is that __builtin_clz(x1)
which is here equal to 587581823
always different random number (some times less than 0) and __builtin_clz(x2)
is always -32
If you look on the gcc documentation for __builtin_ctz
we have:
Built-in Function:
int __builtin_ctz (unsigned int x)
Returns the number of trailing 0-bits in x, starting at the least significant bit position. If x is 0, the result is undefined. [emphasis mine]
Undefined is undefined. The completely arbitrary numbers you see as the result are well within the confines of "undefined".