无限while循环和for循环有什么区别?
我在我读过的许多书中看到了不同的约定,您可以在其中使用任一循环结构创建无限循环,例如:
while()
foo();
for(;;)
foo();
但实际上,我应该了解哪些差异?哪一个更好?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
它们在语义上是等效的。 <代码>(x;y;z) { foo; } 相当于
x; while (y) { foo; z; }
。它们在标准的其他版本中并不完全相同,在 for (int x = 0; y; z) 的示例中,x 的范围是 for块并且在循环结束后超出范围,而 withint x; while (y) x
循环结束后它仍然在范围内。另一个区别是
for
将缺少的y
解释为 TRUE,而while
必须提供表达式。 <代码>for (;;) { foo; } 没问题,但是while() { foo; }
不是。They're semantically the equivalent.
(x;y;z) { foo; }
is equivalent tox; while (y) { foo; z; }
. They're not exactly equivalent in further versions of the standard, in the example offor (int x = 0; y; z)
, the scope ofx
is the for block and is out of scope after the loop ends, whereas withint x; while (y) x
it's still in scope after the loop ends.Another difference is that
for
interprets missingy
as TRUE, whereaswhile
must be supplied with an expression.for (;;) { foo; }
is fine, butwhile() { foo; }
isn not.这是我在调试模式下进行 VS2010 反汇编时看到的一个小差异。不确定是否足以算作显着和普遍真实差异(跨所有编译器和所有优化)。
因此,从概念上讲,这些循环是相同的,但在处理器级别,由于具有无限消息循环,附加/不同指令的时钟周期可能不同,并且会产生一些差异。
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 循环之外,您必须在那里放置一些真实条件,例如
while(1)
。另请参阅:是“用于(;;)”比“while (TRUE)”更快?如果不是,人们为什么要使用它?
而且,“更好”的可能是不是无限的。 :)
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. :)
没有什么区别。
但
不一样
记住!如果你打破了 foo() 语句之前的 while,foo() 不会执行,但如果你打破了 for,foo() 就会执行...
There's no difference.
But
isn't the same that
Remember! If you break the while before the foo() statement, foo() doesn't execute, but if you break the for, foo() executes...
第一个将无法编译。您至少需要:
while( true )
。它们在语义上是等效的。这是风格/个人选择的问题。The first one will not compile. You need at least:
while( true )
. They are semantically equivalent. It is a matter of style/personal choice.它们都是相同的.. 现代编译器为两者发出相同的代码.. 有趣的是(历史上?) for(;;) 更流行.. pascal 程序员曾经做过#define (;;),并且永远使用{/ /代码}
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}