Pascal programming language

Standard scalar types

An integer is a signed 16-bit integer with wrapping semantics, stored as two bytes.

A byte is an unsigned 8-bit integer with wrapping semantics, stored as one byte. They can be used interchangeably with integers, except when passed as parameters.

A real is a floating point value with 11 digits of mantissa, stored as six bytes. Underflowing will cause a result of zero. Overflowing will cause an error, halting the program.

A boolean can have a value of True or False, and is stored as one byte.

A char is a character in the ASCII character set, stored as one byte. Chars are ordered by ASCII value.

Syntax

Valid characters

Valid characters are a-z, A-Z, 0-9, and each of +-*/=^<>()[]{}.,:;'#$. (. and .) are substitutes for [ and ]. (* and *) are substitutes for { and }.

Language elements are delimited by a blank, an end-of-line, or a comment. The maximum length of a program line is 127 characters, with excess characters being ignored.

Identifiers

An identifier is a case-insensitive string of up to 127 letters, digits, or underscores, and cannot begin with a digit.

Numbers

Hexadecimal literals use a $ prefix, as in $1C00.

Real literals can use exponential notation with the letter E, as in 2E-5.

Characters and strings

String literals are delimited with single quotes, as in 'This is a string'. Single quotes can be included in a string by using two consecutive single quotes, as in 'You''re' or ''''. Single-character string literals are stored as a char.

There are two formats for including control characters in a string: a # followed by an integer literal, as in #10 or #$1B, or a ^ followed by a single character, as in ^G or ^[. Control characters can be concatenated with each other or with strings by placing them directly adjacent.

Comments

Comments are delimited with curly braces or with the substitutes (* and *), and cannot be nested.

Compiler directives

Compiler directives are denoted as comments beginning with a $, as in {$I-}. Directives apply to all following lines.

The R directive controls run-time range checks on scalar and subrange variables. The default is {$R-} (disabled).

Program structure

Programs consist of an optional program heading followed by a program block. The block is divided into a declaration part and a statement part.

Program heading

The heading can provide a program name and a list of parameters through which the program communicates with the environment.

program Circle;
program Writer(Input,Printer);

Declaration part

The declaration part of the body contains sections for label declarations, constant definitions, type definitions, variable declarations, and procedure/function declarations. Turbo Pascal allows these sections to occur in any number and in any order.

Label declarations

Label declarations are given as a comma-separated list of label identifiers. Numbers can be used as label identifiers. Any statement in the program may be prefixed with a label (label:), which can then be used by a goto statement.

label 10, start, loop;

Constant definitions

Constant definitions are given as a semicolon-separated list of constant assignments. Constant values can be either strings or numbers.

const
  Limit = 255;
  Password = 'hunter2';

Type definitions

Type definitions are given as a semicolon-separated list of type assignments.

type
  Number = Integer;
  Day = (mon,tues,wed,thur,fri,sat,sun);
  List = array[1..10] of Real;

Variable declarations

Each variable in a program must be declared before use. Variable declaractions are local to the block in which they are declared.

var
  Result, Total: Real;
  X, Y, Z: Integer;
  Period: Day;
  Buffer: array[0..127] of Byte;

Procedure and function declarations

A procedure performs a task, and a function returns a value.

Statement part

The statement part specifies the actions to be executed by the program, and takes the form of a compound statement (begin, followed by a list of semicolon-separated statements, followed by end), followed by a period or semicolon.

Structure

Statements

Conditional statement

if expr then stmt;
if expr then stmt1 else stmt2;

Case statement

case Operator of
  '+': Result := Answer + Result;
  '-': Result := Answer - Result;
  '*': Result := Answer * Result;
  '/': Result := Answer / Result;
end;

case Year of
  min..1999: WriteLn('Early');
  2000..max: WriteLn('Late');
end;

For statement

for I := 2 to 100 do if A[I] > Max then Max := A[I];

to increments, downto decrements. The range is inclusive of the end value. The component statement of a for statement must not contain assignments to the control variable.

While statement

while Size > 1 do Size := Sqrt(Size);

Repeat statement

repeat [...] until [...];

Executes until statement is true. Always executed at least once.

Advanced types

User defined types

Scalar types

Operator = (Plus,Minus,Multiply,Divide);

The relational operators can be applied to all user-defined scalar types, using the definition order (increasing to the right).

The successor (Succ), predecessor (Pred), and ordinal (Ord) functions can be applied to all user-defined scalar types. Ordinals start at 0.

Scalar types with fewer than 256 elements are stored as one byte.

Subrange types

A type can be defined as a subrange of an existing scalar type.

type
  HemiSphere = (North, South, East, West);
  World      = (East..West);
  Upper      = 'A'..'Z';
  Lower      = 'a'..'z';

Elements of an integer subrange contained in the range 0..255 will be stored as one byte.

Array types

Strings

Strings are declared with a maximum length. The length of string cannot exceed 255.

type
  FileName   = string[14];
  ScreenLine = string[80];

String variables occupy a number of bytes equal to the maximum length, plus a length byte. Characters are indexed starting from 1.

Strings are concatenated with + or Concat(a,b,...). If the result exceeds 255 characters, a run-time error occurs.

Strings can be compared with the relational operators.

If a string exceeding the maximum length of a string variable is assigned to the variable, the excesss will be truncated.

Strings can be indexed into using subscript notation, as String[3]. The length of a string can be accessed and modified via String[0]. The length must not be increased beyond the maximum length of the variable. When the length is increased, the added characters will be random.

String procedures

  • Delete(string, index, count)
    Removes count characters from string, starting from index.
  • Insert(object, string, index)
    Inserts the string object into string at index.
  • Str(number, string)
    Converts number into a string, stores the result into string. number is a write parameter (like a format string, see p111).
  • Val(string, variable, code)
    Converts string to a number and stores the result in variable. Leading and trailing whitespace is forbidden. code is an integer variable that will be set to 0 on success, or the index of the first erroneous character on error.

String functions

  • Copy(string, index, count)
    Returns the substring string[index:index+count].
  • Concat(s1, s2, ...)
    Returns the concatenation of all passed string values.
  • Length(string)
    Returns the length of string.
  • Pos(object, string)
    Returns the position of object in string, or 0 if not found.

Arrays

An array is defined with the word array, followed by the index type in square brackets, followed by the word of, followed by the component type.

An array can be indexed by any scalar type.

type
  Players = (Ben, Alex);
var
  mem : array[0..255] of Byte;
  scores : array[Players] of Integer;

Array elements are accessed via subscript notation.

mem[0] := $FF;
scores[Ben] := 5;

Multidimensional arrays

type
  Card = (Two,Three,Four,Five,Six,Seven,Eight,Nine,Ten,Knight,Queen,King,Ace);
  Suit = (Hearts,Spades,Clubs,Diamonds);
  AllCards = array[Suit] of array[1..13] of Card;
var
  Deck: AllCards;

The notation array[Suit,1..13] of Card is equivalent to array[Suit] of array[1..13] of Card, and the notation Deck[Hearts,10] is equivalent to Deck[Hearts][10].

Character arrays

A character array is a constant-length string, and can be used in place of a string.

Predefined arrays

Turbo Pascal provides two predefined arrays of type Byte, called Mem and Port. These are used to access CPU memory and data ports (see chapters 20, 21, and 22).

Record types

type
  DaysOfMonth = 1..31;
  Date = record
           Day: DaysOfMonth;
           Month: (Jan,Feb,Mar,Apr,May,Jun
                   Jul,Aug,Sep,Oct,Nov,Dec);
           Year: 2000..2255;
         end;
var
  Birth: Date;
  WorkDay: array[1..5] of Date;
Birth.Month := Jul;
Birth.Year := 1997;

Tables

Reserved keywords

Words suffixed by * are undefined.

absolute*   external*   nil         shl*
and         file        not         shr*
array       forward     overlay*    string*
begin       for         of          then
case        function    or          type
const       goto        packed      to
div         inline*     procedure   until
do          if          program     var
downto      in          record      while
else        label       repeat      with
end         mod         set         xor*

Predefined identifiers

These are allowed to be overwritten.

Addr         Delay        Length       Release
ArcTan       Delete       Ln           Rename
Assign       EOF          Lo           Reset
Aux          EOLN         LowVideo     Rewrite
AuxInPtr     Erase        Lst          Round
AuxOutPtr    Execute      LstOutPtr    Seek
BlockRead    Exit         Mark         Sin
BlockWrite   Exp          MaxInt       SizeOf
Boolean      False        Mem          SeekEof
BufLen       FilePos      MemAvail     SeekEoln
Byte         FileSize     Move         Sqr
Chain        FillChar     New          Sqrt
Char         Flush        NormVideo    Str
Chr          Frac         Odd          Succ
Close        GetMem       Ord          Swap
ClrEOL       GotoXY       Output       Text
ClrScr       Halt         Pi           Trm
Con          HeapPtr      Port         True
ConInptr     Hi           Pos          Trunc
ConOutPtr    IOresult     Pred         UpCase
Concat       Input        Ptr          Usr
ConstPtr     InsLine      Random       UsrInPtr
Copy         Insert       Randomize    UsrOutPtr
Cos          Int          Read         Val
CrtExit      Integer      ReadLn       Write
CrtInit      Kbd          Real         WriteLn
DelLine      KeyPressed