Pol
Pol

Reputation: 5134

Invoking procedure returned by function

Having this:

procedure Foo;
begin
end;

function Bar: TProcedure;
begin
  Result := Foo;
end;

The following compiles:

var
  tmp: TProcedure;
begin
  tmp := Bar();
  tmp();

...but the following doesn't compile in Delphi:

Bar()();

Is there a reason for this "limitation"? Does Bar()(); syntax compile in some other "flavour" of Pascal? Would Bar()(); syntax compile in some other context?

Upvotes: 5

Views: 167

Answers (2)

David Heffernan
David Heffernan

Reputation: 612784

I don't think there is a limitation in the grammar of the language. The statement Bar()() should be valid. So, I believe that this is a compiler bug in older versions of Delphi. This program compiles in Delphi 2010 and later:

{$APPTYPE CONSOLE}

uses
  SysUtils;

procedure Foo;
begin
end;

function Bar: TProcedure;
begin
  Result := Foo;
end;

begin
  Bar()();
end.

It is quite possible that the compiler bug was fixed before Delphi 2010, it's just that's the version that I have to hand. It seems that the bug is still present in Delphi 7, and fixed by Delphi 2010. So the bug appears to have been fixed somewhere in between those two versions.

Update 1

Marco reports that the Free Pascal compiler accepts Bar()().

Update 2

Rudy has done some testing and reports that the bug is still present in D2007 so the fix was either D2009 and D2010. My instincts tell me that Embarcadero would have discovered the problem themselves when adding the anonymous methods feature and that would have been the trigger for the fix to be made.

Upvotes: 3

Fenistil
Fenistil

Reputation: 3801

Simply call as

TProcedure(Bar());

Upvotes: 6

Related Questions