[fpc-devel] Maybe room for better documentation? open array as var param

Martin Frb lazarus at mfriebe.de
Thu Jul 20 18:41:44 CEST 2023

For const param, it is well documented that the value (that includes the 
variable that is passed) must not be changed.

But for "var param"?

Well maybe, but not explicit
 >> Open parameters can be passed by value, by reference or as a 
constant parameter. In the latter cases the procedure receives a pointer 
to the actual array.

So a user with sufficient experience could detect that if a pointer is 
received, then the value which is pointed to must not be changed.

Maybe that should be mentioned more explicitly.
And maybe it should additionally also be mentioned on 

Because the below may be unexpected to quite a few users.

It will (at least on my test on windows / of course depends on mem 
manager) print numbers starting at 300.
Even so 200++ has been assigned.

But (with sufficient luck or lack of luck) "y" will re-use the memory of 
"x". And "a" will then change "y" which may not be expected.

program Project1;
{$mode objfpc}

var x,y: array of integer;
   i: Integer;

procedure foo(var a: array of integer);
   j: Integer;
   x := nil;
   SetLength(y, 10);
   for j := 0 to 9 do y[j] := 200+j;

   for j := 0 to 9 do a[j] := 300+j;

   SetLength(x, 10);
   for i := 0 to 9 do x[i] := 100+i;
   for i := 0 to 9 do writeln(y[i]);

More information about the fpc-devel mailing list