Why does “for (i = 100; i <= 0; --i)” loop forever?

时光毁灭记忆、已成空白 提交于 2019-12-12 09:46:19

问题


unsigned int i;
for (i = 100; i <= 0; --i)
    printf("%d\n",i);

回答1:


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.




回答2:


Since i is unsigned, it will never be less than zero. Drop unsigned. Also, swap the <= for >=.




回答3:


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.




回答4:


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.




回答5:


The loop checks for i <= 0;

i is never less-than-or-equal to zero. Its initial value is 100.




回答6:


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.




回答7:


I suspect you meant the test to be i > 0.




回答8:


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).




回答9:


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.



来源:https://stackoverflow.com/questions/4788298/why-does-for-i-100-i-0-i-loop-forever

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!