[fpc-devel] Local procedures as procedural parameter

Michael Van Canneyt michael at freepascal.org
Mon Mar 14 10:15:59 CET 2005



On Mon, 14 Mar 2005, Jonas Maebe wrote:

>
> On 14 mrt 2005, at 09:45, Michael Van Canneyt wrote:
>
>>> 7. Consider the following program:
>>> 
>>> 	program func;
>>> 
>>> 	type tfun = function( x: real): real;
>>> 
>>> 	procedure iso_fun( function f( x: real): real);
>>> 	begin
>>> 	end;
>>> 
>>> 	procedure typ_fun( pf: tfun);
>>> 	begin
>>> 	end;
>>> 
>>> 	procedure somefun;
>>> 
>>> 		function f( x: real): real;
>>> 		begin
>>> 		 	f:= x
>>> 		end;
>>> 
>>> 	begin
>>> 		iso_fun( f);
>>> 		typ_fun( f); {procedural variable can't get nested routiine}
>>> 	end;
>>> 
>>> 	begin
>>> 	end.
>> 
>> 1. What happens if f would use a variable from somefun, and f is called
>>    when somefun is no longer executed ?
>
> That is not possible. If you take the address of f and put it in a procedural 
> variable, you'll get an error (just like when you attempt to assign a method 
> to a regular procedural variable). You can only pass it as parameter to 
> procedures declared with an ISO-style procedure/function parameter, and since 
> its scope is limited to somefun, somefun will always be active when you can 
> do so.

But the compiler can never guarantee this ?

It seems to me that the following is perfectly valid code :

Var
   StoredF : Function (x : real) : real

Procedure iso_fun( function f( x: real): real);
begin
   StoredF:=F;
end;

StoredF can then be called at will, even outside somefun.

When compiling this, there is no way the compiler can determine whether
f (or storedf) will be a local procedure or a global one. To solve this,
it would mean that each procedure variable would have to consist of 2
things; A pointer and a type indicator.

This would break _a lot_ of existing code. If that is the consequence, I
am heavily against introducing this possibility.

>
>> 2. I see no difference whatsoever between typ_fun and iso_fun, except
>>    the use of an extra type, which, in my opinion, does not change
>>    anything to the usage or code of these functions. If one is allowed,
>>    the other should be allowed as well.
>
> Well, it currently isn't in either our compiler or in Delphi. You cannot 
> declare a function type inside a parameter list for now. Maybe this was even 
> done on purpose to avoid clashes with ISO-style procedure parameters.

Yes, but why would one be allowed and the other not ?

Michael.




More information about the fpc-devel mailing list