Parameters in Pascal are the variables passed to a function or procedure. Parameters are used to pass data we want to use in a function or procedure. There are four types of parameters in Pascal:
Out parameters are the parameters that are passed to get the output of a function/procedure. The out parameters are passed by reference. Passing parameters by reference means that the function/procedure gets the memory address of the parameters. The changes made to the parameter passed by reference are not discarded when the function/procedure returns, and are propagated back to the calling block.
Variable parameters are also passed to a function/procedure by reference. The difference between variable parameters and out parameters is as follows:
Variable parameters | Out parameters |
---|---|
The initial value of variable parameters before entering the function/procedure is not discarded when entering the function/procedure. This means that the function/procedure can use the current value of its variable parameters. | The initial value of out parameters before entering the function/procedure is discarded when entering the function/procedure. This means that the function/procedure cannot use the current value of its out parameters. |
A variable parameter must be initialized before calling the function/procedure. | It is not required to initialize an out parameter before calling the function/procedure. |
Out parameters are passed to a function using the out
keyword, as follows:
function (out _parameterName_: _parameterType_): _returnType_;
begin
//function body
end
Similarly, out parameters are passed to a procedure using the out
keyword, as follows:
procedure (out _parameterName_: _parameterType_);
begin
//procedure body
end
_parameterName_
: The name of the out parameter._parameterType_
: The data type of the out parameter._returnType_
: The data type of the return value of the function.Note: The
out
keyword is only supported in Delphi and ObjFPC mode.
Consider the code snippet below, which demonstrates the use of out parameters:
{$mode objfpc}program function1;vara, b, calSum : integer;procedure sum(out calSum: integer;var a, b: integer);begincalSum := a+b;end;begina := 5;b := 10;sum(calSum, a, b);writeln(a, ' + ', b, ' = ', calSum);end.
A function sum()
is declared in line 5 and calculates the sum of two numbers passed to it as parameters. The parameters a
and b
passed to the sum()
function are variable parameters, and the parameter calSum
passed to the sum()
function is an out parameter. The return value of the sum
function is stored in calSum
.
Free Resources