0

Here's my code:

int foo() {
  int a = 1;
  while(1) {
    a *=  2;
    printf("a = %d\n", a);
  }
  return a;
}


int main(void) {
  foo();
  return 0;
}

It just keeps printing out "a = 0". I'm confused! Am I missing something really simple?

mkmathur
  • 69
  • 3
  • 1
    It works fine for me ([Link](https://ideone.com/xy4hay)) – Telokis Feb 28 '15 at 02:41
  • 1
    WTF is `while (1)` you intentionally never exit from the loop? – Iharob Al Asimi Feb 28 '15 at 02:43
  • 1
    @iharob I doubt this is the entire actual program. It's probably a simple example designed to show only what the problem is, just like you're supposed to post on SO. – KSFT Feb 28 '15 at 02:44
  • Also to print powers of two you should learn the `<<` operator. – Iharob Al Asimi Feb 28 '15 at 02:44
  • why didn't the OP make the example a simple `for (...)` this bothers me, because i've seen it in very wierd situations where someone deliberately uses `while (1)`... And also, with a simple for like `for (i = 0 ; i < 31 ; i++)` the problem wouldn't happen, would it? – Iharob Al Asimi Feb 28 '15 at 02:50
  • Very similar question in Java: http://stackoverflow.com/q/24173463/1402846 – Pang Feb 28 '15 at 02:54

1 Answers1

6

It overflows to zero, and stays there.

mkmathur
  • 69
  • 3