ZetCode

Pascal style guide

last modified November 19, 2026 Free Pascal 3.2.2

Pascal compiles the same program whether it is indented with two spaces or eight, whether a type is called TInvoice or invoice_type, and whether a parameter is passed by value or by const. Style is therefore a matter of agreement, not of syntax. This guide collects the conventions used in the rest of the series: they aim at code that is easy to read aloud, easy to search, and hard to misuse.

Files and directives

Start every source file with the mode and the string switch, in that order. The program or unit name is lower case and matches the file name, because the compiler and the build tools look for units by name. Put the uses clause after the program header or after interface, never before it, and list only the units the file actually needs.

invoice.pas
unit invoice;
{$mode objfpc}{$H+}

interface

type
  TInvoice = class
  private
    FNumber: string;
    FTotal: Currency;
  public
    property Number: string read FNumber write FNumber;
    property Total: Currency read FTotal write FTotal;
  end;

implementation

end.

The unit name, the file name, and the first identifier inside the file agree. The class fields are private and carry an F prefix, while the properties expose them with the public names. The interface contains no implementation details, so a change to the method bodies does not force the clients to recompile.

Indentation and line length

Use two spaces per level, never tabs. A tab renders differently in every editor and makes diffs noisy. Keep lines under 80 characters; a long expression should be broken after an operator, with the continuation indented by two spaces. begin goes on its own line, and end lines up with the construct it closes. Separate the top-level parts of a file with one blank line: the uses clause, each const, type and var section, each routine, and the main begin. A routine's own var section and its begin stay directly under its header.

if (Count > 0) and (Total > 0) then
begin
  Average := Total / Count;
  WriteLn(Format('average: %.2f', [Average]));
end
else
  WriteLn('no data');

The semicolon separates statements, so there is no semicolon before else and none after the last statement before end. The exception is a record, class, or unit declaration, where the end is followed by a semicolon because the declaration itself is a statement. A single statement after then or else may stay on one line, but a branch that grows to two statements should gain a begin..end block.

Naming

Pascal is case-insensitive, so names must be distinguishable by more than capitalization. Use a T prefix for types, an E prefix for exception classes, an I prefix for interfaces, and an F prefix for fields. Methods and local variables start lower case; parameters get a descriptive name rather than a one-letter abbreviation. Avoid prefixes that repeat the type, such as iCount or strName.

KindConventionExample
TypeT + nounTInvoice, TPoint
Class fieldF + nounFTotal, FItems
Parameternoun, no prefixCustomer, Amount
Local variablenounIndex, Subtotal
Constantnoun, usually capitalizedMaxItems, Pi
Unitlower case, one wordinvoice, csvreader

The prefix is a hint, not a law. A record field that is part of a public property may use the property name without a prefix when the property is the only access path. Do not rename a variable to Data or Value when a more specific word exists; the name is the cheapest documentation a program has.

Parameters and const

Pass small scalars by value. Pass strings, records, and dynamic arrays as const when the routine only reads them, so the compiler can avoid a copy and the caller knows the value will not change. Use var only when the routine must return a second value, and out when the parameter is written before it is read.

procedure PrintTotal(const Invoice: TInvoice);
begin
  WriteLn(Invoice.Number, ': ', Invoice.Total:0:2);
end;

procedure AddItem(var Total: Currency; Amount: Currency);
begin
  Total := Total + Amount;
end;

function TryParseAmount(const Text: string; out Amount: Currency): Boolean;
begin
  Result := TryStrToCurr(Text, Amount);
end;

const is not a promise that the object is immutable: a class reference passed as const still reaches the same object, and its properties can be changed. It only prevents the routine from assigning a new reference to the parameter. For a record with managed fields, const also avoids the hidden copy of the string or array.

Resource management

Every object created with a constructor must be freed, and every lock acquired must be released. Put the cleanup in a finally block immediately after the creation, so an exception can never skip it. Use FreeAndNil when a field or a variable must not be used again after it is freed, because Free alone leaves a dangling pointer.

List := TStringList.Create;
try
  List.LoadFromFile(FileName);
  Process(List);
finally
  List.Free;
end;

Lock.Acquire;
try
  SharedCounter := SharedCounter + 1;
finally
  Lock.Release;
end;

The pattern is the same for files, streams, and threads. A constructor that fails partway through must free what it has already allocated before it propagates the exception; a destructor must be safe to call on a partially constructed object. Free is nil-safe, so a field that was never created can still be freed.

Errors and exceptions

Raise a specific exception class with a message that names the value and the operation. Catch only the exceptions you can handle, and let the rest propagate to the top of the program. An empty except block hides bugs and makes the program continue in an unknown state.

if not FileExists(FileName) then
  raise EFileNotFoundException.CreateFmt('configuration file not found: %s',
    [FileName]);

try
  Config := LoadConfig(FileName);
except
  on E: EInOutError do
    WriteLn('cannot read the configuration: ', E.Message);
end;

The first block fails early, where the problem is still easy to describe. The second catches only the I/O error it expects, so a programming error such as a nil dereference still reaches the debugger. For a command-line program, print the message to standard error and set ExitCode to a non-zero value.

A small program in the house style

The program below puts the rules together: a type with a T prefix, a constant instead of a magic number, a const record parameter, and a single WriteLn with a format string. The record is small enough to pass by value, but const documents that the function only reads it.

style.pas
program style;
{$mode objfpc}{$H+}

uses
  SysUtils;

type
  TTemperature = record
    Celsius: Double;
  end;

const
  BoilingPoint = 100.0;

function Fahrenheit(const Temperature: TTemperature): Double;
begin
  Result := Temperature.Celsius * 9 / 5 + 32;
end;

var
  Water: TTemperature;

begin
  Water.Celsius := BoilingPoint;
  WriteLn(Format('%.1f C = %.1f F',
    [Water.Celsius, Fahrenheit(Water)]));
end.

The record is declared before the constant that uses it, the function appears before the main block that calls it, and the formatted output has a fixed number of decimals. The program has no global variable other than the one it needs, and no comment explains what the code already says.

$ fpc -gl style.pas
$ ./style
100.0 C = 212.0 F

Checklist

Before committing a Pascal file, read it once with these questions in mind. Most of them catch defects that the compiler accepts silently.

The list is short on purpose. A style guide that tries to decide every expression is ignored; these eight points cover the mistakes that cost the most time in a Pascal codebase. The compiling and debugging article shows how to turn the last point into a build step.

Source

Free Pascal Reference guide

Pascal style guide on the Free Pascal wiki

In this article we fixed the file header, indentation, naming, parameter qualifiers, resource cleanup, and exception handling, and put them together in a small program. The procedures and functions article explains the parameter modes, and the unit testing article verifies the result.

Author

I am Jan Bodnar, a programmer and technical writer. I have been writing programming tutorials at ZetCode since 2007 and have published eight e-books. See about the author.

List all Pascal tutorials.