0

This is a simple program, running in a loop, it prints out x + 1 forever

#include <stdio.h>

int main (void)
{
    x = 2;
    while(true)
    {
        x += 1;
        printf("%d\n", x);
    }
}

all is fine here, however, changing the operator to a simple multiplication as in here :

#include <stdio.h>

int main (void)
{
    x = 2;
    while(true)
    {
        x *= 2;
        printf("%d\n", x);
    }
}

outputs nothing but zeros. What am I missing here?

3

It actually prints 4,8,16,32,64 etc. until it hits the maximum integer value of 232-1 and from then on, it can only print 0 because you've overflowed the integer. It happens so quickly that you miss the first numbers.

Try substituting the while loop with a for loop so you can see what happens.

#include <stdio.h>

int main (void)
{
    int x = 2;
    for (int i = 0; i < 33; i++)
    {
        x *= 2;
        printf("%d\n", x);
    }
}
1
  • cool, thank you
    – chaneque
    Jul 17 '14 at 4:07

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .