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 thefunction body.
Examples
Example 1
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.
Explanation
- Lines 5-12: The
sumfunction is declared and takes two input parameters,aandb. The sum function calculates the mathematical sum ofaandbin 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
sumfunction is called in line 17 and is passed withaandbas input parameters. The return value of thesumfunction is then stored in thecalSumvariable.
Example 2
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.
Explanation
- Lines 5-11: The
sumfunction is declared and takes two input parameters,aandb. The sum function calculates the mathematical sum ofaandbin line 10 and stores the sum in a local variable,tempSum. To return a value from a function, we use the keywordexitthat exists from the function and returns its value. - Lines 12-13: Any code in the function body written after
exitis not executed. This is why lines 12-13 are not executed. - Line 19: The
sumfunction is called in line 19 and is passed withaandbas input parameters. The return value of thesumfunction is then stored in thecalSumvariable.
Example 3
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
Copyright ©2026 Educative, Inc. All rights reserved