Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
299 views
in Technique[技术] by (71.8m points)

c - Is there some reason for this kind of for-loop?

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...