Assuming two's complement, 1 << 31
results in a negative value, so your test for i > 0 fails immediately with the first test. You most likely would have had more luck with i != 0
then.
But we aware that 1 << 31
is a signed integer overflow, which is undefined behaviour anyway! So you should do 1U << 31
instead, too. If you assign this then positive value to a signed int, which is not capable to hold it, you have again undefined behaviour. So the correct for loop would look like this:
for(unsigned int i = 1U << 31; i > 0; i /= 2)
Although i /= 2
for unsigned values is equivalent to a bitshift (and is likely to be compiled to), I would prefere the bitshift operation explicitly here (i >>= 1
), as this is what you actually intend.