How to increment counter in for loop? (Pascal)
Asked Answered
F

2

5

I have a big issue because this piece of code was compiling correctly in Dev-Pascal but not in Lazarus.

 for k:=1 to n do
     begin
          writeln(a[k]:4:2,'  ',a[k+1]:4:2,'  ',a[k+2]:4:2);
          inc(k,2);
     end;

I'm getting this message

Error: Illegal assignment to for-loop variable "k"

What I should do now? I need this solutions (incrementing k counter) in my program.

Frier answered 11/1, 2017 at 19:13 Comment(1)
What about for k := 0 to n div 3 - 1 do begin writeln(a[k * 3 + 1]:4:2, ' ', a[k * 3 + 2], ... ? That is what I would do, if I had to access 3 elements on each iteration.Roseliaroselin
L
7

Actually, I think it is more a case of Dev-Pascal letting you get away with it whereas quite rightly FP does not. The reason that the compiler will not usually let you modify the for variable within the loop is that it can subvert the code the compiler generates to determine when the upper for value has been reached.

Add a local variable j, assign it the same starting value as k, increment it by 2 inside the for loop and use j as your array indexer instead of k.

Latona answered 11/1, 2017 at 19:37 Comment(3)
"increment it by 2 inside" - sorry, I don't get it. Can you explain that thing?Frier
Inc(j, 2) or j := j + 2Latona
Thanks! But finally I do this with repeat loop. k:=1; repeat writeln(a[k]:4:2,' ',a[k+1]:4:2,' ',a[k+2]:4:2); inc(k,3); until k>=n;Frier
C
0

Delphi does not allow modification of the loop variable, TP does. In its own modes FPC follows Delphi because that is the sane thing to do because of the reasons that MartynA listed frustrate optimization.

However FPC does allow it in Turbo Pascal mode for old codebases, add {$mode tp} or compile with -Mtp

Compartment answered 12/1, 2017 at 11:44 Comment(1)
TP didn't, AFAIK. At least the latest versions (TP7, TP6, TPW1.5, etc.) didn't.Roseliaroselin

© 2022 - 2024 — McMap. All rights reserved.