What is the condition for this “for(;;)” loop? [duplicate]

做~自己de王妃 提交于 2020-01-04 09:19:08

问题


Can someone explain what is the condition for this for loop?

for(;;) {
 //do sth.
}

回答1:


It has no condition. It's an infinite loop.




回答2:


If the test condition is empty (and it is here), there is no test and the loop continues indefinitely. It's a short form for an infinite loop.




回答3:


It is an infinite loop as the condition is empty.

From the java specs If the Expression is not present, then the only way a for statement can complete normally is by use of a break statement. As you don't have condition and break so your its an infinite loop.




回答4:


This is an infinite for loop with no condition. The for loop contains following semantics

for(loop variable initialization ; condition to terminate ; variable increment)

Since there is nothing in between then two ';'its no condition infinite loop




回答5:


It is equal to this:

while(true){
 //do sth.
}

which is an infinite loop.




回答6:


If you tries to decompile this simple program

for(;;){
    System.out.println("yes");
}

You will get this one as result:

do
   System.out.println("yes");
while(true);

I'm using this decompile tool: JAD Java Decompiler (dont work for Java 8+)




回答7:


As everyone said, it is an infinite loop. A simple way to see that it is an infinite loop is to look the for(;;) statement in byte code.

Take this reference class:

public class Test {
    public static void main (String[] args){
        for(;;){}
    }
}

The compiler output (in bytecode):

public class Test {
  public Test();
    Code:
       0: aload_0       
       1: invokespecial #1                  // Method java/lang/Object."<init>":()V
       4: return        

  public static void main(java.lang.String[]);
    Code:
       0:
         goto 0
}

The goto 0 jumps at the label 0, which is above line. This process will never stops.




回答8:


The three expressions of the for loop are optional, an infinite loop can be created as follows:

// Infinite loop
for ( ; ; ) {
   // Your code goes here
}


来源:https://stackoverflow.com/questions/26653968/what-is-the-condition-for-this-for-loop

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