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

可紊 提交于 2019-12-18 04:59:11

问题


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();
for(;;)
   foo();

But really, what are the differences I should know about? which one is better?


回答1:


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.




回答2:


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**
} 



回答3:


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




回答4:


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




回答5:


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




回答6:


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}



来源:https://stackoverflow.com/questions/3535822/what-is-the-difference-between-infinite-while-loops-and-for-loops

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