Every time our program uses the computer’s memory, there’s a possibility that there was already something in that memory location. While the memory manager makes sure that the memory we’re using isn’t still being used by some other part of the program, it doesn’t always guarantee that there isn’t still “leftover” data there.

Here’s how it works:

When you create a local variable (var MyVar: Integer), its initial value is undefined. It will have the value of whatever was in that memory location from before. You should always assign it a value when using it, except….

Local reference-counted variables (Strings, Interfaces, dynamic arrays) ARE initialized with an “empty” value (empty string, nil, etc…).

When you create a new object (i.e. MyVar := TMyObject.Create), all of the fields of the object are initialized to 0 or “empty.” Any numeric fields are zero, strings are empty strings, references to other objects, interfaces, etc… are nil. Boolean fields are false.

GLOBAL variables (in the var section of a unit, not the var section of a procedure or function) are initialized to 0 or empty when the application starts.

Want to see your code the way the compiler does? Check out Castalia, a smarter code editor for Delphi, integrated right into the Delphi IDE.