'How to handle overflow of unsigned int in C? [closed]

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 }


Solution 1:[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;

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 abelenky