When working with FPC 3.2.3 (Lazarus 4.0 RC1) I noticed that the variable handling in for
loops does not work as expected:
for i:=0 to 10 do Log(IntToStr(i));
Log('@end:'+IntToStr(i));
returns:
(compiler optimization level 0): 0 1 2 3 4 5 6 7 8 9 10 @end:10 (compiler optimization level 1): 0 1 2 3 4 5 6 7 8 9 10 @end:10 (compiler optimization level 2): 0 1 2 3 4 5 6 7 8 9 10 @end:10 (compiler optimization level 3): 0 1 2 3 4 5 6 7 8 9 10 @end:0
I would have expected the value 11
in the 2nd log (after the end of the loop), just like in C, for example. Can any of you (also in other Lazarus versions) reproduce this?
When working with FPC 3.2.3 (Lazarus 4.0 RC1) I noticed that the variable handling in for
loops does not work as expected:
for i:=0 to 10 do Log(IntToStr(i));
Log('@end:'+IntToStr(i));
returns:
(compiler optimization level 0): 0 1 2 3 4 5 6 7 8 9 10 @end:10 (compiler optimization level 1): 0 1 2 3 4 5 6 7 8 9 10 @end:10 (compiler optimization level 2): 0 1 2 3 4 5 6 7 8 9 10 @end:10 (compiler optimization level 3): 0 1 2 3 4 5 6 7 8 9 10 @end:0
I would have expected the value 11
in the 2nd log (after the end of the loop), just like in C, for example. Can any of you (also in other Lazarus versions) reproduce this?
2 Answers
Reset to default 2From the Free Pascal Wiki:
Note that the value of the "for loop variable" is undefined after a loop has completed or if a loop is not executed at all.
Since you're running the loop to completion, the value is undefined. Optimization level 3 leaves it at the initial value (it's probably unrolling the loop and not updating the variable at all) while others simply omit the last increment.
Yes, according to wiki it is normal. The compiler also points out that i may not be initialized. However, this is incorrect in this case, as i is a local variable that was initialized at the start of the for loop, even if the end value was specified as the start value. I pointed this out because it is handled differently in other programming languages, which has the advantage that the value following the loop end value is directly available. Here you can help yourself by calculating end value+1 yourself and using it in the 2nd log. if the loop is exited prematurely, for example, you do not know up to which value the loop was run through.
for
loops - at worst the compiler optimization reverses the iteration (and having a loop target of0
can be faster CPU wise). If you rely on the variable's content then usewhile
andrepeat
loops only. This also applies to other compilers, like Native and Delphi. – AmigoJack Commented 14 hours ago