+ 2

[SOLVED] Why is the code part infinite?

This is an infinite loop. for(unsigned i=0; i >=0; i--) { // do work ... }

4th Sep 2021, 4:36 PM
mesarthim
mesarthim - avatar
4 ответов
+ 8
That’s because an unsigned int can only be a positive number. i already equals 0, it cannot go into negatives. i will always be greater than or equal to zero, so the check i >= 0 will always return true. It’s effectively the same as: for (;;). Here’s an example that is not infinite, using a signed int which allows negatives: for (int i = 0; i >= -10; --i) { printf("%d", i); }e Abhay explains below, that on the decrement iteration where i equals zero, the counter goes back to the max positive value, like an odometer.
4th Sep 2021, 4:45 PM
DavX
DavX - avatar
+ 3
It does not only remains zero as i thought . Look at the example , for(unsigned int i=0;i>=0;i--){ printf("%lu\n",i); } It will start decrementing from the max value of unsigned int after we try to make the number negative .
4th Sep 2021, 5:26 PM
Abhay
Abhay - avatar
+ 2
As i is unsigned data type so its value never become negative so it becomes infinite
4th Sep 2021, 6:33 PM
Mohd Aadil
Mohd Aadil - avatar
+ 1
Thanks for all explanations! :) DavX , Abhay , Mohd Aadil .
4th Sep 2021, 6:42 PM
mesarthim
mesarthim - avatar