Hi all, I have a procedure which needs to be used by a wide range of functions.

I have a created a very basic program which should highlight my problem :

program untitled;

function addnumbers(num1 : integer) : integer;
begin
result := num1 + 3;
end;

procedure sequence(I want the function to go here);

var

i : integer;

begin
for i := 1 to 100 do
begin
Writeln(addnumbers(i)); // the function which appears here is a parameter stated in the brackets of the function
end;

end;

begin
sequence(function name) // I want to be able to input a function here
end.

Basically I have a really complex procedure (100+ lines) which needs to be used by many functions. Instead of writing an exact copy of the procedure every time (just with different function within it) I was wondering whether the function can be called by stating it as a parameter in the procedure.

e.g.

begin
sequence(function goes here);
end.

Thanks for any help,

Greg

Recommended Answers

All 4 Replies

Use function pointer. This might help...

TMyFunctionPrototype = function (num1 : integer) : integer of object;
  ...
  procedure sequence(my_func : TMyFunctionPrototype);
  begin
  ...
  if Assinged(my_func) then
    begin
        //do something with my_func
        my_func(5);
    end;
  ... 
  end;
  function addnumbers(num1 : integer) : integer;
  begin
     result := num1 + 3;
  end;
  ...
  begin
     sequence(addnumbers);
  end;

Thanks this helped. Although I found out that in the compiler I'm using (Lazarus) an @ symbol is needed when pointing to a function.

Thanks very much,

Greg

I've seen that thread already solved but I have a question
Where is the connection between addnumbers and the sequence?
Listen my code it is works too,but I cannot see the connection

program untitled;

function addnumbers(num1:integer):integer;
begin
  addnumbers:=num1+3;
end;

procedure sequence(num2:integer);
var i:integer;
begin
     for i:=1 to 100 do begin
         writeln(addnumbers(i));
     end;
end;

begin (*main*)
     sequence(addnumbers(10));
     readln;
end.
(*created by FlamingClaw 2010.03.09*)

In your code you pass to sequence a value which is returned from addnumbers(10). He wanted to pass a pointer to function which he can call in the body of sequence. In this way he could pass any function. I know this is not the best example since it does nothing particular, but you may declare 3 functions:

function addnumbers(num1:integer):integer;
begin
  addnumbers:=num1+3;
end;

function addnumbers2(num1:integer):integer;
begin
  addnumbers:=num1*num1 + 33;
end;

function addnumbers3(num1:integer):integer;
begin
  addnumbers:=num1*num1*num1+333;
end;

...and pass any one of them to sequence in order to get something different done.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.