How to declare a function in Pascal

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.

Examples

Example 1

Consider a simple example of a function that returns the sum of two numbers:

program function1;
var
a, b, calSum : integer;
function sum(a, b: integer): integer;
var
tempSum: integer;//local Declaration
begin
tempSum := a + b;
sum := tempSum;//store return value in variable having same name as the name of function
end;
begin
a := 5;
b := 10;
calSum := sum(a, b);
writeln(a, ' + ', b, ' = ', calSum);
end.

Explanation

  • Lines 5-12: The 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.
  • Line 17: The 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.

Example 2

Another way to return a value from a function is to use the exit keyword, as shown below:

program function2;
var
a, b, calSum : integer;
function sum(a, b: integer): integer;
var
tempSum: integer;//local Declaration
begin
tempSum := a + b;
exit(tempSum);
tempSum := tempSum + 50;
sum := tempSum
end;
begin
a := 5;
b := 10;
calSum := sum(a, b);
writeln(a, ' + ', b, ' = ', calSum);
end.

Explanation

  • Lines 5-11: The 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.
  • Lines 12-13: Any code in the function body written after exit is not executed. This is why lines 12-13 are not executed.
  • Line 19: The 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.

Example 3

Consider an example of a function with no input parameters:

program function3;
function noParam(): integer;
begin
writeln('This is a function with no parameters');
noParam := 0;
end;
begin
noParam();
end.

Free Resources

Copyright ©2025 Educative, Inc. All rights reserved