4.5 Initializing variables using default

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