Can a for loop be written to create an infinite loop or is it only while loops that do that?

前端 未结 12 1467
时光取名叫无心
时光取名叫无心 2021-01-17 23:58

Can a for loop be written in Java to create an infinite loop or is it only while loops that cause that problem?

相关标签:
12条回答
  • 2021-01-18 00:33

    You can also do such with for loops. E.g. the following is identical to while(true):

    for(;;) {
    }
    
    0 讨论(0)
  • 2021-01-18 00:38

    Apart from issues of scope and one other thing, this:

    for(<init>; <test>; <step>) {
      <body>
    }
    

    is the same as:

    <init>
    while(<test>) {
      <body>
      <step>
    }
    

    As other people have alluded to, in the same way that you can have a while loop without an <init> form or <step> form, you can have a for loop without them:

    while(<test>) {
      <body>
    }
    

    is the same as

    for(;<test>;) {
      <body>
    } //Although this is terrible style
    

    And finally, you could have a

    for(;true;) {
      <body>
    }
    

    Now, remember when I said there was one other thing? It's that for loops don't need a test--yielding the solution everyone else has posted:

    for(;;) {
      <body>
    }
    
    0 讨论(0)
  • 2021-01-18 00:42
    for(;;){}
    

    is same as

    while(true){}
    
    0 讨论(0)
  • 2021-01-18 00:42

    Dont forget mistakes like

    for (int i=0; i<30; i++)
    {
        //code
       i--;
    }
    

    It's not as uncommon as it should be.

    0 讨论(0)
  • 2021-01-18 00:46

    I'll just add this since nobody did this version:

    for(;;);
    
    0 讨论(0)
  • 2021-01-18 00:47

    Ofcourse for loops can cause infinite loops. An example is:

    for(int i = 0; i < 99; i /= 2){ ... }

    Because i is never incremented, it will stay in the body of the for loop forever until you quit the program.

    0 讨论(0)
提交回复
热议问题