Variable Parameters (Vars)

Parameters used so far have been "passed by value". We used the example

procedure WriteStars(NumberOfStars: integer);

This was called in the DrawStars program with the statement WriteStars(TitleLength);. The value of TitleLength is passed to the local variable NumberOfStars. If this procedure were to modify NumberOfStars with a statement such as dec(NumberOfStars);, it would not change the global variable TitleLength. Sometimes we want global variables to take the value of the parameters when they change. This can be achieved using variable parameters such as Int1 and Int2 in the following example.

program Addition;
  Num1, Num2, Sum : integer;

procedure InputNumbers(var Int1, Int2 : integer);    //var indicates variable parameters 
  write('Please enter the first integer to add. '); 
  write('Please enter the second integer to add. '); 

  InputNumbers(Num1, Num2);
  Sum := Num1 + Num2;
  writeln('Sum: ',Sum);

In this case the parameters have been "passed by reference". The addresses of Int1 and Int2 rather than their values are passed to the procedure InputNumbers.

A procedure can include code to change global variables without using variable parameters. The procedure InputNumbers could have used the statements readln(Num1); and readln(Num2);. The use of variable parameters is recommended because it makes it clear that global variables are being modified by the procedure. Suppose we wanted the procedure InputNumbers to have third variable parameter Real1, a real number. The procedure heading would need to be

procedure InputNumbers(var Int1, Int2 : integer; var Real1 : real);

because the first var takes effect only up to the first semicolon. Procedures can use variable parameters in combination with parameters passed by value. For example:

procedure Calculate(Num1, Num2 : real; var Sum, Difference: real);

The keyword out can be used instead of var to indicate a variable parameter.

Features introduced:
  • Calling by value
  • Calling by reference
  • Variable parameters
  • Use of var and out keywords
Programming - a skill for life!

Introduction to Procedures and Functions