What is the difference between infinite while loops and for loops?

前端 未结 6 1756
忘掉有多难
忘掉有多难 2020-12-18 04:24

I see the different conventions used in many books I had read, where you would create infinite loops with either loop structure such as:

while()
   foo();
fo         


        
相关标签:
6条回答
  • 2020-12-18 04:42

    There's no difference.

    Except in the while loop, you have to put some true condition there, e.g. while(1).

    See also: Is "for(;;)" faster than "while (TRUE)"? If not, why do people use it?

    Also, the "better" one might be the one that isn't infinite. :)

    0 讨论(0)
  • 2020-12-18 04:45

    they're both the same.. modern compilers emit identical code for both.. interestingly (historically?) the for(;;) was more popular.. pascal programmers did a #define (;;) ever, and used forever {//code}

    0 讨论(0)
  • 2020-12-18 04:48

    Here is one small difference I saw with the VS2010 disassembly in debug mode. Not sure, if it is sufficient enough to count as a significant and universally true difference (across all compiler and with all optimizations).

    So conceptually these loops are same, but at a processor level, with infinite message loops, the clock cycles for the additional/different instructions could be different and make some difference.

       while(1)
    004113DE  mov         eax,1                       **// This is the difference**
    004113E3  test        eax,eax                     **// This is the difference**
    004113E5  je          main+2Eh (4113EEh)  
          f();
    004113E7  call        f (4110DCh)  
    004113EC  jmp         main+1Eh (4113DEh)          **// This is the difference**
       for(;;)
          f();
    004113EE  call        f (4110DCh)  
    004113F3  jmp         main+2Eh (4113EEh)          **// This is the difference**
    } 
    
    0 讨论(0)
  • 2020-12-18 04:49

    The first one will not compile. You need at least: while( true ). They are semantically equivalent. It is a matter of style/personal choice.

    0 讨论(0)
  • 2020-12-18 04:52

    They're semantically the equivalent. (x;y;z) { foo; } is equivalent to x; while (y) { foo; z; }. They're not exactly equivalent in further versions of the standard, in the example of for (int x = 0; y; z), the scope of x is the for block and is out of scope after the loop ends, whereas with int x; while (y) x it's still in scope after the loop ends.

    Another difference is that for interprets missing y as TRUE, whereas while must be supplied with an expression. for (;;) { foo; } is fine, but while() { foo; } isn not.

    0 讨论(0)
  • 2020-12-18 04:59

    There's no difference.

    But

    while() foo();

    isn't the same that

    for(;;foo();)

    Remember! If you break the while before the foo() statement, foo() doesn't execute, but if you break the for, foo() executes...

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