可一个空的for循环是"正确"? [英] Can an empty for-loop be "correct"?
问题描述
我有一个关于在C以下code回路的疑问:
I have a doubt about the for loop of the following code in C:
main()
{
int i=1;
for(;;)
{
printf("%d",i++);
if(i>10)
break;
}
}
我看到了试卷此code。我认为for循环将无法工作,因为它在它没有条件。但得到的答复说,code有没有错误。是真的吗?如果为真,如何?
I saw this code in a question paper. I thought that the for loop won't work because it has no condition in it. But the answer says that the code has no error. Is it true ? If true, how ?
推荐答案
for循环经常有三部分:
The regular for loop has three parts:
- 初始化
- 条件
- 递增
通常他们这样写的:
for (initialization; condition; increment) { statements }
但是,所有三部分都是可选的。在你的情况,所有部分都确实是从丢失的循环,,但present其他的:
- 的初始化是
INT I = 1
- 的条件是
如果(我大于10)破
- 增量为
我++
- The initialization is
int i=1
- The condition is
if (i>10) break
- The increment is
i++
以上code,可等价地写为:
The above code can be equivalently written as:
for (int i=1; i <= 10; i++) {
printf("%d", i);
}
因此,所有必需的for循环的部分是present,只是它们不是实际的的内部
结构。这个循环的工作,它只是不写一个非常可读的方式。
So all the parts necessary for a for loop are present, except they are not inside the actual for
construct. The loop would work, it's just not a very readable way to write it.
这篇关于可一个空的for循环是&QUOT;正确&QUOT;?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!