Functions in Pascal

Functions are central in Pascal. We’ll learn about functions with a few different examples.

program Functions;

uses
  SysUtils;

// Here's a function that takes two integers and returns
// their sum as an integer.
function Plus(a, b: Integer): Integer;
begin
  // Pascal automatically returns the value of the last expression,
  // but we can use an explicit Result assignment for clarity.
  Result := a + b;
end;

// In Pascal, we don't need to specify the type for each parameter
// if they share the same type.
function PlusPlus(a, b, c: Integer): Integer;
begin
  Result := a + b + c;
end;

// The main program block in Pascal
begin
  // Call a function just as you'd expect, with name(args).
  WriteLn('1+2 = ', Plus(1, 2));
  
  WriteLn('1+2+3 = ', PlusPlus(1, 2, 3));
end.

To run this program, save it as functions.pas and compile it using a Pascal compiler like Free Pascal:

$ fpc functions.pas
$ ./functions
1+2 = 3
1+2+3 = 6

In Pascal, functions are defined using the function keyword, followed by the function name, parameter list, and return type. The function body is enclosed between begin and end keywords, with the end followed by a semicolon.

Pascal uses a begin...end block for the main program, which is similar to the main() function in other languages.

Unlike some modern languages, Pascal requires explicit variable declarations. However, in this simple example, we didn’t need to declare any variables as we’re just calling functions and printing their results.

Pascal’s WriteLn procedure is used for console output, similar to fmt.Println in the original example.

There are several other features to Pascal functions. One is the ability to use reference parameters, which we’ll look at next.