When you call SetLength you don't need to initialize the array before hand. SetLength ensures the uniqueness of the array (lazy copy behavior), so no matter what could have been done previously to that array, as long as you don't care what is written into the array there is no need to initialize an array before calling setlength.
There is an exception to this and that is the
Result variable as already hinted at by
MountainQ's initial post.
Take the following example:
program tarrtest;
{$modeswitch result}
type
TLongIntArray = array of LongInt;
function Test1: TLongIntArray;
begin
Result := [1, 2, 3];
end;
function Test2: TLongIntArray;
begin
SetLength(Result, 5);
end;
var
l: TLongIntArray;
i: LongInt;
begin
l := Test1;
for i in l do
Write(i, ' ');
Writeln;
l := Test2;
for i in l do
Write(i, ' ');
Writeln;
end.
This will result in the following output:
1 2 3
1 2 3 0 0
Thus if you expect the elements of
Result to be 0 in
Test2, that assumption is incorrect.
This behaviour is
intended and by design (and can also happen in Delphi). This also applies if the result type is one of the managed
String types (
AnsiString,
UnicodeString).
So for the
Result variable it's safest to set a dynamic array to
Nil.
For local variables I've questioned the hint on the core mailing list in the past already, but
fpk did not agree with me.