Search code examples
cfor-loopbit-manipulationbitwise-operatorsbit-shift

Why does this for loop in C program print Hi 11 times?


#include <stdio.h>
int main()
{
int i = 1024;
for (; i; i >>= 1)
printf("Hi");
return 0;
}

Why does the for loop print Hi 11 times? I don't understand.


Solution

  • The expression i >>= 1 is equivalent to i = i / 2

    So if initially i is equal to 1024 then the body of the loop will be executed for the values

    1024 512 256 128 64 32 16 8 4 2 1
    

    that is 11 times. The value of the expression 1 / 2 is equal to 0 due to the integer arithmetic.

    You could check that by changing the call of printf like

    #include <stdio.h>
    
    int main( void )
    {
        int i = 1024;
    
        for (; i; i >>= 1) printf( "%d ", i );
    
        putchar( '\n' );
    }