Multiple Return Values in Pascal

Pascal has built-in support for multiple return values through the use of var parameters. This feature is often used in idiomatic Pascal to return both result and error values from a function.

program MultipleReturnValues;

uses
  SysUtils;

procedure Vals(var a, b: Integer);
begin
  a := 3;
  b := 7;
end;

var
  a, b, c: Integer;

begin
  { Here we use the 2 different return values from the
    call with var parameters. }
  Vals(a, b);
  WriteLn(a);
  WriteLn(b);

  { If you only want a subset of the returned values,
    you can simply ignore one of the variables. }
  Vals(c, c);
  WriteLn(c);
end.

To run the program, save it as multiple_return_values.pas and use the Pascal compiler:

$ fpc multiple_return_values.pas
$ ./multiple_return_values
3
7
7

In Pascal, we use var parameters to achieve multiple return values. The Vals procedure modifies its parameters directly, which are then accessible in the calling scope.

If you only want a subset of the returned values, you can simply ignore one of the variables or reuse the same variable for both parameters, as demonstrated with c.

Pascal doesn’t have a built-in concept of a blank identifier like in some other languages. Instead, you can use a dummy variable or reuse an existing variable if you don’t need one of the return values.

Accepting a variable number of arguments is another feature available in some Pascal compilers through the use of open array parameters; we’ll look at this in a future example.