Why does "for (i = 100; i <= 0; --i)" loop forever?
unsigned int i;
for (i = 100; i <= 0;开发者_开发技巧 --i)
printf("%d\n",i);
Should be i >= 0
in the second condition in the loop if you want it to loop from 100 to 0.
That, and as others have pointed out, you'll need to change your definition of i
to a signed integer (just int
) because when the counter is meant to be -1, it will be some other positive number because you declared it an unsigned int
.
Since i
is unsigned, it will never be less than zero. Drop unsigned
. Also, swap the <=
for >=
.
Since i
is unsigned, the expression i <= 0
is suspicious and equivalent to i == 0
.
And the code won't print anything, since the condition i <= 0
is false on its very first evaluation.
If the code is supposed to do nothing, nothing is wrong with it.
Assuming that you want it to print the loop index i
from 100 to 1, you need to change i <= 0
to i > 0
.
Because it is an unsigned int, you cant use i >= 0
because that will cause it to infinitely loop.
The loop checks for i <= 0;
i
is never less-than-or-equal to zero. Its initial value is 100.
Technically nothing is wrong with that code. The test for i <= 0 is strange since i is unsigned, but it's technically valid, true when i is 0 and false otherwise. In your case i never happens to be 0.
I suspect you meant the test to be i > 0
.
The <= 0 maybe? since it is false
from the start
For loop
- init: i = 100
- test: i <= 0 // false on first pass
Change the test to i > 0
(100 times)
or i >= 0
(101 times) together with the declaration signed int i;
so that it actually decreases down to -1. An unsigned int will go from 0 up to max-int (overflow).
If you want it to print all numbers from 100 down to 0 then you need
unsigned int i;
for (i = 100; i >= 0; --i)
printf("%d\n",i);
The first time your loop ran in your original code, i was 100. The test '100 <= 0' failed and therefore nothing was showing.
精彩评论