Results 1 to 4 of 4

Thread: Object/variable initialization

  1. #1

    Object/variable initialization

    Is there a compiler switch or something to force all object variables' initial value to nil?

    For example:
    Code:
    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;
    If you develop an idiot proof system, the nature develops better idiots.

  2. #2

    Object/variable initialization

    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/radstu...spart_xml.html

    [pascal]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;[/pascal]

  3. #3

    Object/variable initialization

    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.

  4. #4

    Object/variable initialization

    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.

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •