Functions in Pascal are declared using the function
keyword, as shown in the code snippet below:
function _funcName_ (_parameter(s)_: _parameterType_;, _parameter(s)_: _parameterType_;, ...): _returnType_;
_localDeclarations_
begin
//function body
end;
_functionName_
: The name of the function._argument(s)_
: The input parameters that are passed to the function._parameterType_
: The data type of the arguments passed._returnType_
: The return data type of the function._localDeclarations_
: Declarations such as variables, constants, functions, etc., that are referred to in the function body
.Consider a simple example of a function that returns the sum of two numbers:
program function1;vara, b, calSum : integer;function sum(a, b: integer): integer;vartempSum: integer;//local DeclarationbegintempSum := a + b;sum := tempSum;//store return value in variable having same name as the name of functionend;begina := 5;b := 10;calSum := sum(a, b);writeln(a, ' + ', b, ' = ', calSum);end.
sum
function is declared and takes two input parameters, a
and b
. The sum function calculates the mathematical sum of a
and b
in line 10 and stores the sum in a local variable, tempSum
. To return a value from a function, we assign the return value to a variable with the name of the function.sum
function is called in line 17 and is passed with a
and b
as input parameters. The return value of the sum
function is then stored in the calSum
variable.Another way to return a value from a function is to use the exit
keyword, as shown below:
program function2;vara, b, calSum : integer;function sum(a, b: integer): integer;vartempSum: integer;//local DeclarationbegintempSum := a + b;exit(tempSum);tempSum := tempSum + 50;sum := tempSumend;begina := 5;b := 10;calSum := sum(a, b);writeln(a, ' + ', b, ' = ', calSum);end.
sum
function is declared and takes two input parameters, a
and b
. The sum function calculates the mathematical sum of a
and b
in line 10 and stores the sum in a local variable, tempSum
. To return a value from a function, we use the keyword exit
that exists from the function and returns its value.exit
is not executed. This is why lines 12-13 are not executed.sum
function is called in line 19 and is passed with a
and b
as input parameters. The return value of the sum
function is then stored in the calSum
variable.Consider an example of a function with no input parameters:
program function3;function noParam(): integer;beginwriteln('This is a function with no parameters');noParam := 0;end;beginnoParam();end.
Free Resources