PDA

View Full Version : Object/variable initialization



vgo
17-09-2008, 12:47 PM
Is there a compiler switch or something to force all object variables' initial value to nil?

For example:


procedure Foo;
var
x: TObject;
begin
// Just making sure it's nil and I want to get rid of these checks
x := nil;
....
if Assigned(x) then
FreeAndNil(x);
...
end;

User137
17-09-2008, 02:00 PM
By default new variables that are not public or class variables, are not nil or 0 at first.

Seeing list here didn't show any such:
http://docs.codegear.com/docs/radstudio/radstudio2007/RS2007_helpupdates/HUpdate4/EN/html/devcommon/delphicompdirectivespart_xml.html

var public_n: byte; // this variable is 0

procedure Foo;
var n: byte;
begin
// at the moment n is anything from 0 to 255
...
end;

michalis
18-09-2008, 12:19 AM
Global variables are always initialized to zero/nil/false etc. Local variables are filled with random garbage, so you have to keep these "x := nil" initializations inside procedures, if you depend on them. This is true for both FPC and Delphi (but I don't know about Delphi .NET flavors).

That said, you don't have to check "if Assigned(x)" before calling FreeAndNil. FreeAndNil is guaranteed to do nothing if x is already nil. So you can remove these checks.

masonwheeler
18-09-2008, 01:36 PM
Yeah. Free won't cause trouble if it's a nil pointer. However, if you pass it an invalid pointer, (random garbage value or an object that's already been freed,) it'll raise exceptions. So no need to check Assigned, but the nil initialization at the start should still be there.