A function is self-contained unit of code in Pascal (and other languages) that returns a single value to the point from which it is called. We are used to the idea of assignment in a statement such as:
a:=12;
or
a:=b/2;
and so on.
A function is most likely to perform a calculation that is:
As an example, take the calculation of factorials. In an environment where factorials are in use it is likely that they will be needed quite often so it would be useful to be able to write something like:
p:=factorial(m)/factorial(n);
rather than to have to write out the calculation in full for each factorial every time one is needed.
We might, therefore, define a function to calculate factorials as follows:
function factorial(n:integer):integer;
var i,f: integer;
begin
f:=1;
if n<=0 then factorial := 1
else
for i:= 1 to n do
f:=f * i;
factorial:=f;
end;
The function header does the following:
The rest of the code is ordinary Pascal. The function has its own begin..end structure, with optional type, const and var sections according to its needs. The body of the function goes between the begin and end and is largely standard Pascal.
The result of the function can be returned to the point from which it was called by two means:
This function might be called as follows:
edit2.text:=inttostr(factorial(strtoint(edit1.text)))
That is, convert the contents of edit1 to an integer, feed these into the factorial function and then convert the integer result into a string that is displayed in edit2.
In Delphi this code would be placed in the Implementation section of a unit, just above the procedure where from which it is first called.
implementation
{$R *.dfm}
function factorial(n:integer):integer;
var i,f: integer;
begin
f:=1;
if n<=0 then factorial := 1
else
for i:= 1 to n do
f:=f * i;
factorial:=f;
end;
procedure TForm1.Button1Click(Sender: TObject);
begin
edit2.text:=inttostr(factorial(strtoint(edit1.Text)));
end;
Further examples of functions will occur later in the tutorial.