3

可能重复:
“for(;;)”是否比“while (TRUE)”快?如果不是,人们为什么要使用它?

使用此 for 循环找到代码。例如,使用它的具体功能是什么while(true)?它使用更少的内存吗?

4

4 回答 4

11

for(;;)在功能上等同于while(true)但避免了某些编译器(包括 MSVC 的 cl)的“条件表达式是常量”警告

于 2013-01-18T13:03:39.223 回答
3

Kernighan 和 Ritchie 在他们的C 编程语言书(第 3.5 节)中推广了这种结构

for 语句

for (expr1; expr2; expr3)
    statement

如果 expr1 或 expr3 被省略,它只是从扩展中删除。如果测试 expr2 不存在,则认为它是永久正确的,所以

for (;;) {
    ...
}

是一个“无限”循环,可能会被其他方式打破,例如 a breakor return.

for(;;)和之间绝对没有区别while(true)

于 2013-01-18T13:04:29.967 回答
1
while(true)
{

}

始终是我使用过的以及我看到其他人使用的必须手动破坏的循环。

一些编译器给你警告,这虽然织机可能是不正确的。但事实并非如此。

为两者生成的汇编代码完全相同。没有区别。

于 2013-01-18T13:04:15.037 回答
1

首先,循环的使用取决于需求&基于此,我们只能决定何时使用哪一个。只需检查@Luchian 的要求,您就会知道。

其次,这显然取决于特定语言的解释器/编译器的特定实现。

That said, theoretically, any sane implementation is likely to be able to implement one in terms of the other if it was faster so the difference should be negligible at most.

于 2013-01-18T13:09:42.087 回答