-1

How can I change line 6 to handle the integer overflow so that this code will never terminate (while still increasing i in each loop iteration)?

1 int main() {
2    unsigned int i;
3    i = 1;
4    while (i > 0) {
5        printf("%u \n", i);
6        i *= 2;
7    }
8    printf("%u \n", i);
9 }
robertsni
  • 1
  • 1

1 Answers1

1

Because i is unsigned, it is never less than zero, but it may at some point be zero.

I might try to guarantee it is always at least 1 with something like this:

i = i*2? i*2 : 1;

That is:
If i*2 is non-zero, then that is the new value of i.
Otherwise, i*2 would be zero, so instead set i = 1;

abelenky
  • 63,815
  • 23
  • 109
  • 159