无限while循环和for循环有什么区别? [英] What is the difference between infinite while loops and for loops?

查看:175
本文介绍了无限while循环和for循环有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到我读过的许多书中使用的不同约定,你可以使用以下两种循环结构创建无限循环:

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?

推荐答案

它们在语义上是等价的。 (x; y; z){foo; } 等效于 x; while(y){foo; z; } 。在 for(int x = 0; y; z)的示例中,的范围不同于标准的其他版本> x 是for块,在循环结束后超出范围,而 int x;

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.

另一个区别是 for 解释缺少 y 为TRUE,而必须提供一个表达式。 for(;;){foo; } 很好,但 while(){foo; } isn not。

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.

这篇关于无限while循环和for循环有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆