+ 2
[SOLVED] Why is the code part infinite?
This is an infinite loop. for(unsigned i=0; i >=0; i--) { // do work ... }
4 Respostas
+ 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.
+ 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 .
+ 2
As i is unsigned data type so its value never become negative so it becomes infinite
+ 1