这种for-loop有什么理由吗? [英] Is there some reason for this kind of for-loop?
问题描述
有没有理由在c中写这样的for循环?
(第一个语句留空,高度设置在外部,而这个高度变量在这个地方之后也没有使用)
$ pre code> lastheight = halfheight;
。
。 //更多的代码更改高度,包括设置
。 // lastheight
。 //实际上就是墙壁的高度
。
height = halfheight;
for(; lastheight< height; lastheight ++)
只要您对循环语法的 完全有效,只要 引用烦恼, b
$ b $ p $ for(; lastheight< height; lastheight ++)
lastheight
在之前被定义和初始化。
C11
,第6.8.5.3章
for(clause-1; expression-2; expression-3)语句
[... ] clause-1 和 expression-3 都可以省略。省略的表达式-2 由
非零常量替换。
关于为循环定义 lastheight
的原因 ,可以提到的一点是,对于像
这样的构造,(int lastheight = 0; lastheight< height; lastheight ++ ){...} // C99及以上
限制范围 lastheight
到for循环体。如果你想在循环体的<范围之外之后使用 lastheight
,你必须在循环之外定义
另外,如果我的内存在C99之前正常工作,那么在语句的中不可能声明一个变量。所以,要走的路是
int lastheight;
for(lastheight = 0; lastheight< height; lastheight ++){...}
另外,这里有一个关于的详细讨论的链接, / code>循环语法。
声明:我的回答。
Is there some reason to write a for-loop like this in c? (first statement is left empty and height is set outside instead.. and that height variable is not used after this elsewhere either)
lastheight = halfheight;
.
. // some more code changing height, includes setting
. // lastheight
. // to something that is essentially the height of a wall
.
height = halfheight;
for ( ; lastheight < height ; lastheight++)
It is referenced from Wolfenstein3D source code.
As long as you're bothered with the for
loop syntax,
for ( ; lastheight < height ; lastheight++)
is perfectly valid, as long as lastheight
is defined and initialized previously.
Quoting C11
, chapter §6.8.5.3
for ( clause-1 ; expression-2 ; expression-3 ) statement
[...] Both clause-1 and expression-3 can be omitted. An omitted expression-2 is replaced by a nonzero constant.
Regarding the reason for defining lastheight
outside the for
loop, one thing can be mentioned, that, for a construct like
for ( int lastheight = 0 ; lastheight < height ; lastheight++) {...} //C99 and above
limits the scope of lastheight
to the for loop body. If you want lastheight
to be used after (outside the scope of) the loop body, you must have the definition outside the loop.
Also, if my memory serves correctly, before C99, declaration of a variable was not possible inside the for
statement, anyway. So, the way to go was
int lastheight;
for ( lastheight = 0 ; lastheight < height ; lastheight++) {...}
Also, here's a link to a detailed discussion about for
loop syntax.
Disclaimer: My answer.
这篇关于这种for-loop有什么理由吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!