The below code runs perfectly.Gives the correct output but, the moment I change the sign of the variables from signed to unsigned the program runs into an infinite loop. The
As other answers already noted, the loop
for(i=count-1;i>=0;--i)
is an infinite loop if i
is unsigned. It can be rewritten in a different form as
for (i = count - 1; i != -1; --i)
which will work as intended for both signed and unsigned i
. However, some might find it less readable than the original.
An unsigned int
can never be negative, so i >= 0
holds true
all the time, that means that a loop like
unsigned int value;
value = 10;
while (value-- >= 0) {}
is effectively an inifinte loop, as well as your for (i = count - 1 ; i >= 0 ; --i)
is.
Compilers do warn about this, so if you compile your code passing the right flags to the compiler, it should tell you that the condition will be always true.
You should note that while the >=
makes no difference in this respect,
unsigned int value;
value = 10;
while (value-- != 0) {}
does work, as while (value-- > 0)
also does, because value
can be 0
, but it can't be < 0
.
There is also, no unsigned int
integer overflow, so the loop will be infinite without causing undefined behavior, this answer has an explanation of what happens when you add 1
to the maximum value, if you subtract one from the minimum value, then I am sure you can "guess" what would happen from the same answer.
The problem is that,
for(i=count-1;i>=0;--i)
Will never exit if i
is unsigned. Because i
is unsigned it will always be greater than or equal to zero, and thus the loop can't end.