Главная страница | назад





Article #17677: Passing a function to a procedure or vice versa.

 Question and Answer Database

FAQ2677D.txt   Passing a function to a procedure or vice versa.
Category   :Object Pascal
Platform    :All
Product    :All 32 bit  

Question:
Can I pass a function or procedure to another function or
procedure?


Answer:
Yes. You must declare a procedure or function type to use 
as the parameter type, then you can pass the address of the 
procedure that you wish to pass. You must be careful to 
pass functions or procedures that are compatible with the 
function or procedure expected, as little error checking 
will be provided by the compiler.

Example:

type
  AFunctionType = function(IntIn : integer) : integer;

function AddProc(IntIn : integer) : integer;
begin
  Result := IntIn + 1;
end;

function SubProc(IntIn : integer) : integer;
begin
  Result := IntIn - 2;
end;

procedure PassAFunction(var IntIn : integer;
                       fn : AFunctionType);
begin
  IntIn := fn(IntIn);
end;

procedure TForm1.Button1Click(Sender: TObject);
var
  i : integer;

begin
  i := 10;

  PassAFunction(i, @AddProc);
  ShowMessage(IntToStr(i));

  PassAFunction(i, @SubProc);
  ShowMessage(IntToStr(i));
end;

7/16/98 4:31:28 PM
 

Last Modified: 01-SEP-99