For loop with no parameters in Java

扶醉桌前 提交于 2019-12-21 08:05:38

问题


I am looking at somebody else's code and I found this piece of code:

for (;;) {

I'm not a Java expert; what is this line of code doing?

At first, I thought it would be creating an infinite loop, but in the very SAME class this programmer uses

while(true)

Which (correct me if I'm wrong) IS an infinite loop. Are these two identical? Why would somebody change their method to repeat the same process?

Any insight would help,

Thanks!


回答1:


Remember the three clauses of the for() are [1] initialization [2] termination and [3] increment. Since the termination clause is empty the loop never terminates. This is directly taken from C syntax.




回答2:


Those two lines would have the same effect. I can't think of a good reason to use the first one unless you like to confuse people. I guess it's less characters.




回答3:


they are entirely the same the only real difference would be either preference (the for construct can be typed marginally faster)

or the for indicates that is is some iteration that is broken out of by a break or return and a while loop indicates a repeating section of the same thing until a meaningful result appears



来源:https://stackoverflow.com/questions/6051869/for-loop-with-no-parameters-in-java

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