What are variable parameters in Pascal?

Parameters in Pascal are the variables passed to a function or procedure. We use parameters to pass data we want to use in a function or procedure. There are four types of parameters in Pascal:

Variable parameters

Variable parameters are parameters that 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.

Syntax

Variable parameters are passed to a function using the var keyword, as follows:

function (var _parameterName_: _parameterType_): _returnType_;
begin
   //function body
end

Similarly, variable parameters are passed to a procedure using the var keyword, as follows:

procedure (var _parameterName_: _parameterType_);
begin
   //procedure body
end
  • _parameterName_: The name of the variable parameter.
  • _parameterType_: The data type of the variable parameter.
  • _returnType_: The data type of the return value of the function.

Note: As changes made to the variable parameters are propagated back to the calling block, care must be taken when using variable parameters.

Code

Consider the code snippet below, which demonstrates the use of the variable parameters.

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

Explanation

A function sum() is declared in line 5 that calculates the sum of two numbers passed to it as parameters. The parameters passed to the sum() function are variable parameters. This is why changing the value of the parameter a is propagated back when the function returns.

Copyright ©2024 Educative, Inc. All rights reserved