Search code examples
delphisubroutine

Are mainfunction's parameters and variables safe to use inside a subroutine?


Could main function's parameters and variables be used inside subroutines or is there something wrong in doing this?

procedure TForm1.FormCreate(Sender: TObject);
var
  Test : string;
  procedure SubFnTest();
  begin
    ShowMessage(Self.Name);
    ShowMessage(TForm1(Sender).Name);
    ShowMessage(Test);
  end;
begin
  Test := 'hello';
  SubFnTest();
end;

I'm testing this code on Delphi-2007 now and it seems there's no problem, but I have some faint memory about troubles caused by this practices (I don't really remember which was the problem at that time)


Solution

  • Your code is absolutely fine. Nested functions can refer to variables from outer scopes.

    I suspect that what you are remembering is that it is not permitted to use a nested function as a procedural value. For instance, see the discussion of that topic here: Why cannot take address to a nested local function in 64 bit Delphi?