Functions and Return Values

The first example of a function uses one parameter, CircleRadius. Note that the return type of the function (in this case real) must be given in the function heading.

There are two ways of assigning the return value: the value to be returned by the function can be assigned to
  • the in-built local variable with identifier result, or
  • a variable with the same identifier as the function:
    CircleArea := 3.142 *  CircleRadius * CircleRadius;

In the program below, the value to be returned by the function is assigned to the in-built local variable with identifier result.

program RealFunction;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Radius, Area : real;

function CircleArea (CircleRadius : real) : real;
begin
  result := 3.142 *  CircleRadius * CircleRadius;
end;

begin
  write('Please enter radius of circle. ');
  readln(Radius);
  Area := CircleArea(Radius);
  writeln('Area = ',Area:8:2);
  readln;
end.

Note that the name of the variable holding the argument (Radius) is not the same as the name of the parameter (CircleRadius).

The following program has a function with two parameters of the same type. It shows that the arguments supplied to the function can be either hard-coded values (in this case 24 and 36) or variables (Int1 and Int2).

The function is declared with the following statement:

function Mean(Num1, Num2 : integer) : real;

The function is called with the expression Mean(Int1, Int2). The first argument (the value of Int1), is passed to Num1 and the second (the value of Int2) is passed to Num2.

program FunctionArguments;
{$APPTYPE CONSOLE}
uses
  SysUtils;
var
  Int1,Int2 :integer;

function Mean(Num1, Num2 : integer) : real;
begin
  result := (Num1 + Num2) / 2;
end;

begin
  // Using values as arguments
  writeln('The mean of 24 and 36 is ', Mean(24, 36) : 6 : 1);
  write('Please enter your first integer ');
  readln(Int1);
  write('Please enter your second integer ');
  readln(Int2);
  // Using variables as arguments
  writeln('The mean of  ', Int1, ' and ', Int2, ' is ', Mean(Int1, Int2) : 6 : 1);
  readln;
end.

Features introduced:
  • Syntax for declaring a function
  • How to call a function
  • Two ways of assigning the return value
Programming - a skill for life!

Introduction to Procedures and Functions