这种for循环有什么理由吗?

mge*_*ear -2 c syntax for-loop

有没有理由在c中写这样的for-loop?(第一个语句留空,高度设置在外面而且......高度变量在其他地方之后也没用过)

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++)
Run Code Online (Sandbox Code Playgroud)

它是从Wolfenstein3D源代码中引用的.

Sou*_*osh 5

只要你对for循环语法感到困扰,

 for ( ; lastheight < height ; lastheight++)
Run Code Online (Sandbox Code Playgroud)

只要lastheight先前已定义和初始化,它就完全有效.

引用C11,章节§6.8.5.3

for ( clause-1 ; expression-2 ; expression-3 ) statement
Run Code Online (Sandbox Code Playgroud)

[...] 可以省略子句-1表达式3.省略的表达式-2由非零常量替换.


关于在循环外定义的原因,有一点可以提到,对于像这样的构造lastheightfor

 for ( int lastheight = 0 ; lastheight < height ; lastheight++)  {...} //C99 and above
Run Code Online (Sandbox Code Playgroud)

限制范围lastheightfor循环体.如果你想lastheight使用的循环体(范围外),你必须有外循环的定义.

此外,如果我的记忆正确,在C99之前for,无论如何都不能在声明中声明变量.所以,要走的路是

 int lastheight;
 for ( lastheight = 0 ; lastheight < height ; lastheight++)  {...}
Run Code Online (Sandbox Code Playgroud)

另外,这里是关于for循环语法的详细讨论的链接.

免责声明:我的回答.