Some variables must be initialized because they contain managed types. For variables
that are declared in the var section of a function or in the main program, this happens
automatically. For variables that are allocated on the heap, this is not necessarily the
case.
For this, the compiler contains the Default intrinsic. This function accepts a type identifier as the
argument, and will return a correctly initialized variable of that type. In essence, it will zero out
the whole variable.
The following gives an example of its use:
type
TRecord = record
i: LongInt;
s: AnsiString;
end;
var
i: LongInt;
o: TObject;
r: TRecord;
begin
i := Default(LongInt); // 0
o := Default(TObject); // Nil
r := Default(TRecord); // ( i: 0; s: '')
end.
The case where a variable is allocated on the heap, is more interesting:
type
TRecord = record
i: LongInt;
s: AnsiString;
end;
var
i: ^LongInt;
o: ^TObject;
r: ^TRecord;
begin
i:=GetMem(SizeOf(Longint));
i^ := Default(LongInt); // 0
o:=GetMem(SizeOf(TObject));
o^ := Default(TObject); // Nil
r:=GetMem(SizeOf(TRecord));
r^ := Default(TRecord); // ( i: 0; s: '')
end.
It works for all types, except the various file types (or complex types containing a file
type).
Remark
- For generics, the use of Default is especially useful, since the type of a variable may
not be known during the declaration of a generic. For more information section 8.7,
page 501.
- Function results are available as a Result identifier, and as such resemble variables.
They are not variables, but are treated as passed-by-reference parameters. They are
therefore not initialized.