[fpc-devel] Maybe room for better documentation? open array as var param
Martin
laz-test at m-friebe.de
Sat Jul 22 21:36:41 CEST 2023
On 20/07/2023 18:41, Martin Frb via fpc-devel wrote:
> 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"?
Actually my previous example was not even the generic case.
Passing any variable that is allocated on the Heap (a field of an
instance, an element of an array) as a "var param" has the danger that
it can be freed.
And yes, it should be obvious. If you intent to write to a variable, you
must not destroy it.
However, you must also be aware, that in case of an array, if you just
resize it, it may move => yet your var param will not follow that move.
I think it may be "interesting" enough to deserve a small note.
--------------
The below should brinte 200 to 209.
But it does print a 999 in the middle.
program Project1;
{$mode objfpc}
var x,y: array of integer;
i: Integer;
procedure foo(var a: integer);
var
j: Integer;
begin
x := nil;
SetLength(y, 10);
for j := 0 to 9 do y[j] := 200+j;
a := 999;
end;
begin
SetLength(x, 10);
for i := 0 to 9 do x[i] := 100+i;
foo(x[5]);
for i := 0 to 9 do writeln(y[i]);
readln;
end.
More information about the fpc-devel
mailing list