P. 1
Turbo_Pascal_Reference_Manual_Feb84

Turbo_Pascal_Reference_Manual_Feb84

|Views: 150|Likes:
Published by garak1701

More info:

Published by: garak1701 on Mar 23, 2011
Copyright:Attribution Non-commercial

Availability:

Read on Scribd mobile: iPhone, iPad and Android.
download as PDF, TXT or read online from Scribd
See more
See less

06/30/2013

pdf

text

original

Sections

  • The Pascal Language
  • TU RBO Pascal
  • Structure of This Manual
  • Typography
  • Syntax Descriptions
  • USING THE TURBO SYSTEM
  • 1.1 .COM and .CMD files
  • 1.2 BEFORE USE
  • 1.3 Compiler Directive Defaults
  • 1.4 Files On The Distribution Disk
  • Starting TURBO Pascal 1.5
  • 1.5 Starting TURBO Pascal
  • 1.6.1 IBM PC Screen Installation
  • Non-IBM PC Screen Installation 1.6.2
  • 1.6.2 Non-IBM PC Screen Installation
  • 1.6.3 Installation of Editing Commands
  • 1.7.1 Logged Drive Selection
  • 1 .7.1 Logged Drive Selection
  • 1.7.5 Compile Command
  • 1.8 The TURBO Editor
  • 1.B.3 A Note on Control Characters
  • 1.B.4 Before You Start: How To Get Out
  • 1.B.5 Cursor Movement Commands
  • 1.B.5.2 Extended Movement Commands
  • 1.8.6 Insert and Delete Commands
  • 1.8.6.2 Simple Insert/Delete Commands
  • 1.8.7 Block Commands
  • 1.B.B Miscellaneous Editing Commands
  • 1.9 The TURBO editor vs. WordStar
  • 1.9.1 Cursor Movement
  • 1.9.2 Mark Single Word
  • End Edit 1.9.3
  • 1.9.3 End Edit
  • 1 .9.4 Line Restore
  • 1.9.5 Tabulator
  • 1.9.6 Auto Indentation
  • BASIC LANGUAGE ELEMENTS 2
  • 2. BASIC LANGUAGE ELEMENTS
  • 2.1 Basic Symbols
  • 2.2 Reserved Words
  • BASIC LANGUAGE ELEMENTS 37
  • 2.3 Standard Identifiers
  • Delimiters 2.4
  • 2.4 Delimiters
  • 2.5 Program lines
  • 3.1 Integer
  • 3.4 Boolean
  • 3.5 Char
  • 4. USER DEFINED LANGUAGE ELEMENTS
  • 4.1 Identifiers
  • 4.2 Numbers
  • 4.3 Strings
  • Control Characters 4.3.1
  • 4.3.1 Control Characters
  • 4.4 Comments
  • 4.5 Compiler Directi,:,es
  • PROGRAM HEADING AND PROGRAM BLOCK 5
  • S. PROGRAM HEADING AND PROGRAM BLOCK
  • S.1 Program Heading
  • S.2 Declaration Part
  • PROGRAM HEADING AND PROGRAM BLOCK 47
  • 5.2.1 Label Declaration Part
  • 5.2.2 Constant Definition Part
  • 5.2.3 Type Definition Part
  • 5.2.4 Variable Declaration Part
  • 5.2.5 Procedure and Function Declaration Part
  • 5.3 Statement Part
  • EXPRESSIONS 6
  • 6. EXPRESSDONS
  • 6.1 Operators
  • 6.1.1 Unary Minus
  • 6.1.2 Not Operator
  • 6.1.3 Multiplying Operators
  • 6.1.4 Adding Operators
  • 6.2 Function Designators
  • 6.2 F unction Designators
  • STATEMENTS 7
  • 7.1 Simple Statements
  • STATEMENTS 55
  • 7.1.2 Procedure Statement
  • Structured Statements 7.2
  • 7.2 Structured Statements
  • 7.2.2 Conditional Statements
  • 7.2.3 Repetitive Statements
  • SCALAR AND SUBRANGE TYPES 8
  • 8. SCALAR AND SUBRANGE TYPES
  • 8.1 Scalar Type
  • SCALAR AND SUBRANGE TYPES 63
  • 8.2 Subrange Type
  • 8.3 Type Conversion
  • 8.4 Range Checking
  • STRING TYPE 9
  • 9. STRING TYPE
  • 9.1 String Type Definition
  • 9.2 String Expressions
  • 9.3 String Assignment
  • String Procedures 9.4
  • 9.4 String Procedures
  • String Functions 9.5
  • 9.5 String Functions
  • 9.5.1 Copy
  • 9.5.3 Length
  • 9.5.4 Pos
  • Strings and Characters 9.6
  • 9.6 Strings and Characters
  • 10.1 Array Definition
  • 10.2 Multidimensional Arrays
  • 10.3 Character Arrays
  • 10.4 Predefined Arrays
  • 11.1 Record Definition
  • With Statement 11.2
  • 11 .2 With Statement
  • 11.3 Variant Records
  • 12.1 Set Type Definition
  • 12.2 Set Expressions
  • 12.2.1 S~t Constructors
  • Set Operators 12.2.2
  • 12.2.2 Set Operators
  • 12.3 Set Assignments
  • 13.1 Unstructured Typed Constants
  • 13.2 Structured Typed Constants
  • 13.2.1 Array Constants
  • Multidimensional Array Constants 13.2.2
  • 13.2.2 Multidimensional Array Constants
  • 13.2.3 Record Constants
  • 13.2.4 Set Constants
  • 14.1 File Type Definition
  • 14.2 Operations on Files
  • 14.2.9 Erase
  • 14.2.10 Rename
  • File Standard Functions 14.3
  • 14.3 File Standard Functions
  • 14.3.1 EOF
  • 14.4 Using Files
  • 14.5 Text Files
  • 14.5.2 Logical Devices
  • 14.5.3 Standard Rles
  • 14.6 Text File Input and Output
  • 14.6.1 Read Procedure
  • 14.6.2 Readln Procedure
  • Write Procedure 14.6.3
  • 14.6.3 Write Procedure
  • Writeln Procedure 14.6.4
  • 14.6.4 Writeln Procedure
  • 14.7 Untyped Files
  • 14.7.1 BlockRead / BlockWrite
  • 14.8 I/O checking
  • 15.1 Defining a Pointer Variable
  • 15.2 Allocating Variables (New)
  • 15.3 Mark and Release
  • 15.4 Using Pointers
  • Space Allocation 15.5
  • 15.5 Space Allocation
  • PROCEDURES AND FUNCTIONS 16
  • 16. PROCEDURES AND FUNCTIONS
  • 16.1 Parameters
  • PROCEDURES AND FUNCTIONS 121
  • Relaxations on Parameter Type Checking 16.1.1
  • 16.1.1 Relaxations on Parameter Type Checking
  • 16.1.2· Untyped Variable Parameters
  • Procedures 16.2
  • 16.2 Procedures
  • 16.2.1 Procedure Declaration
  • Standard Procedures 16.2.2
  • 16.2.2 Standard Procedures
  • 16.2.2.1 ClrEol
  • 16.2.2.5 Delay
  • 16.2.2.8 GotoXY
  • 16.2.2.9 LowVideo
  • 16.2.2.10 Norm Video
  • A. CP/M-SO
  • A.1 compiler Options
  • A.T.T Memory / Com file / cHn-file
  • A.1A Find Runtime Error
  • A.2 Standard Identifiers
  • A.3 Absolute Variables
  • A.4 Addr Function
  • A.S Predefined Arrays
  • A.6 Array Subscript Optimization
  • A.7 With Statements
  • A.8 Pointer Related Items
  • Pointers and Integers A.B.2
  • A.9 External Subprograms
  • A.10 Chain and Execute
  • A.11 In-line Machine Code
  • A.12 CP/M Function Calls
  • A.T 2.3 Bios procedure and function
  • A.1 2.3 Bios procedure and function
  • A.14 Interrupt Handling
  • Internal Data Formats A.15
  • A.15.2.3.2 Text Files
  • A.15.3 Parameters
  • A.15.3.1 Variable Parameters
  • A.15.3.2 Value Parameters
  • A.1S.3.2.1 Scalars
  • A.15.3.2.3 Strings
  • A.1S.3.2.3 Strings
  • Arrays and Records A.15.3.2.6
  • A.1S.3.2.6 Arrays and Records
  • A.15.4 Function Results
  • A.16 Memory Management
  • A.16.1.1 Compilation in Memory
  • A.16.1.2 Compilation To Disk
  • A.16.2 The Heap and The Stacks
  • MS-DOS/PC-DOS and CP/M-86 B
  • B. MS-DOS/PC-DOS and CP/M-a6
  • B.1 Common features
  • MS-DOS/PC-DOS and CP/M-86 173
  • Minimum Code Segment Size 8.1.1.2
  • 8.1.1.2 Minimum Code Segment Size
  • 8.1.1.3 Minimum Data Segment Size
  • 8.1.1.4 Minimum Free Dynamic Memory
  • B.1.1.5 Maximum Free Dynamic Memory
  • 8.1.2 Standard Identifiers
  • B.1.4 Absolute Address Functions
  • B.l.8 External Subprograms
  • 8.1.9 Chain and Execute
  • B.1.10 In -line Machine Code
  • B.1.11 Interrupt Handling
  • B.1.11.1 Intr procedure
  • Internal Data Formats 8.1.12
  • 8.1.12 Internal Data Formats
  • 8.1.12.1.1 Scalars
  • B.1.12.1.2 Reals
  • 8.1.12.1.2 Reals
  • 8.1.12.1.3 Strings
  • 8.1.12.1.4 Sets
  • 8.1.12.1.5 Pointers
  • 8.1.12.2 Data Structures
  • B.1.12.2.1 Arrays
  • 8.1.12.2.1 Arrays
  • 8.1.12.2.2 Records
  • 8.1.12.2.3 Disk Files
  • B.1.12.2.4 Text Files
  • 8.1.12.3 Parameters
  • 8.1.12.3.1 Variable Parameters
  • 8.1.12.3.2 Value Parameters
  • Scalars 8.1.12.3.2.1
  • B.1.12.3.2.1 Scalars
  • B.1.12.3.2.2 Reals
  • B.1.12.3.2.3 Strings
  • B.1 .12.3.2.4 Sets
  • B.1.12.3.2.5 Pointers
  • B .1.12.3.2.6 Arrays and.Records
  • B.1 .1 2.4 Function Results
  • 8.1.12.4 Function Results
  • B.2 The MS-DOS / PC-DOS Implementations
  • 8.2 The MS-DOS / PC-DOS Implementations
  • 8.2.1 Standard Identifiers
  • 8.2.2 Function Calls
  • 8.2.3 User Written I/O Drivers
  • B.2.4 File Interface Blocks
  • B.2.4 file Interface Blocks
  • 8.2.5 Random Access Rles
  • B.2.6 Operations on Files
  • B.2.6.1 Extended File Size
  • B.2.6.2 File of Byte
  • B.2.6.3 Flush Procedure
  • The CP/M-86 Implementation B.3
  • B.3 The CP/M -86 Implementation
  • 8.3.1 Standard Identifiers
  • 8.3.2 Function Calls
  • 8.3.3 User Written I/O Drivers
  • 8.3.5 Random Access Rles
  • C.1 Input/Output Procedures and Functions
  • C.2 Arithmetic Functions
  • C.3 Scalar Functions
  • C.4 Transfer Functions
  • String Procedures and Functions
  • C.s String Procedures and Functions
  • C.6 File handling routines
  • SUMMARY OF COMPILER DIRECTIVES E
  • E. SUMMARY OF COMPILER DIRECTIVES
  • SUMMARY OF COMPILER DIRECTIVES 213
  • E.1 Common Compiler Directives
  • E.1.2 C -Control Sand C
  • E.1.3 I -I/O Error Handling
  • E.2 CP/M-BO Compiler Directives
  • E.2.1 A -Absolute Code
  • E.2.2 W -Nesting of With Statements
  • E.2.3 X -Array Optimization
  • K -Stack Checking E.3.1
  • E.3 CP/M-a6/ MS-DOS / PC-DOS Compiler Directives
  • £.3.1 K -Stack Checking
  • TURBO Vs. STANDARD PASCAL F
  • F. TURBO VS. STANDARD PASCAL
  • F.2 Recursion
  • FA Goto Statements
  • F.4 Goto Statements
  • F.S Page Procedure
  • F.S Packed Variables
  • F.7 Procedural Parameters
  • COMPILER ERROR MESSA GES G
  • G. COMPILER ERROR MESSAGIES
  • RUN-TIME ERROR MESSAGES H
  • H. RUN-TIME ERROR MESSAGES
  • RUN-TIME ERROR MESSAGES 225
  • I/O ERROR MESSAGES
  • TRANSLATING ERROR MESSAGES J
  • J. TRANSLATING ERROR MESSAGES
  • J.1 Error Message File Usting
  • J.1 Error Message File Listing
  • K. TURBO SYNTAX
  • ASCII TABLE L
  • L. ASCII TABLE
  • M. HELP!! !
  • TERMINAL INSTALLATION N
  • N.1 IBM PC Display Selection
  • N.2 Non-IBM PC Installation

.

)) BORLAnD
.) INTERNATIONAL
Borland International
4113 Scotts Valley Drive
Scotts Valley, California 95066
Copyright Notice ©
This software package and manual are copyrighted 1983, 1984 by BORLAND
INTERNATIONAL Inc. All rights reserved worldwide. No part of this publication
may be reproduced, transmitted, transcribed, stored in any retrieval system,
or translated into any language by any means without the express written per-
mission of BORLAND INTERNA TlONAL Inc., 4113 Scotts Valley Drive, Scotts Valley,
CA 95066, USA.
Single CPU License
The price paid for one copy of TURBO Pascal licenses you to use the product
on one CPU when and only when you have signed and returned the License
Agreement printed in this book.
Disclaimer
Borland International makes no warranties as to the contents of this manual
and specifically disclaims any implied warranties of merchantability or fitness
for any particular purpose. Borland International further reserves the right to
make changes to the specifications of the program and contents of the ma-
nual without obligation to notify any person or organization of such changes.
Second edition, February 1984
Printed in the United States of America
987654321
INTRODUCTION ............................................. 1
The Pascal Language ......................................... 1
TURBO Pascal .............................................. 1
Structure of This Manual ..................................... 2
Typography ............................................... 3
Syntax Descriptions ......................................... 4
1. USING THE TURBO SYSTEM ............................ 5
1.1 .COM and .CM D files ..................................... 5
1.2 BEFORE USE ........................................... 5
1.3 Compiler Directive Defaults ................................ 5
1.4 Files On The Distribution Disk .............................. 6
1.5 Starting TURBO Pascal ................................... 7
Installation ............................................. 8 1.6
1.6.1
1.6.2
1.6.3
1.7
1.7.1
1.7.2
1.7.3
1.7.4
1.7.5
1.7.6
1.7.7
1.7.8
1.7.9
1.7.10
1.7.11
1.8
1.8.1
1.8.2
1.8.3
1.8.4
1.8.5
1.8.5.1
1.8.5.2
1.8.6
1.8.6.1
1.8.6.2
1.8.6.3
IBM PC Screen Installation ............................... 8
Non-IBM PC Screen Installation ........................... 9
Installation of Editing Commands .......................... 9
TheMenu ............................................. 13
Logged Drive Selection ................................. 14
Work File Selection .................................... 14
Main File Selection .................................... 15
Edit Command ....................................... 16
Compile Command .................................... 16
Run Command ....................................... 16
Save Command ...................................... 16
eXecute Command .................................... 17
Directory Command ................................... 17
Quit Command ...................................... 17
compiler Options ..................................... 17
The TURBO Editor ...................................... 18
The Status Line ....................................... 18
Editing Commands .................................... 19
A Note on Control Characters ............................ 21
Before You Start: HowTo Get Out ........................ 21
Cursor Movement Commands ........................... 21
Basic Movement Commands ............. ; ............. 21
Extended Movement Commands ........................ 24
Insert and Delete Commands ............................ 26
Insert or Overwrite? .................................. 26
Simple Insert/Delete Commands ........................ 27
Extended Delete Command ............................ 27
TABLE OF CONTENTS I
1.8.7 Block Commands ..................................... 28
1.8.8 Miscellaneous Editing Commands ........................ 30
1.9 The TURBO editor VS. WordStar ........................... 34
1.9.1 Cursor Movement ..................................... 34
1.9.2 Mark Single Word ..................................... 34
1.9.3 End Edit ............................................ 35
1.9.4 Line Restore ......................................... 35
1.9.5 Tabulator ............................................ 35
1.9.6 Auto Indentation ...................................... 35
2. BASIC LANGUAGE ELEMENTS ......................... 37
2.1 Basic Symbols ......................................... 37
2.2 Reserved Words ....................................... 37
2.3 Standard Identifiers ..................................... 38
2.4 Delimiters ............................................ 39
2.5 Program lines .......................................... 39
3. STANDARD SCALAR TYPES ...............•........... 41
3.1 Integer ............................................... 41
3.2 Byte .......................... ',' ..................... 41
3.3 Real ............................ ' ..................... 42
3.4 Boolean .............................................. 42
3.5 Char ................................................. 42
4. USER DEFINED LANGUAGE ELEMENTS .....•.......... 43
4.1 Identifiers ............................................. 43
4.2 Numbers .............................................. 43
4.3 Strings ............................................... 44
4.3.1 Control Characters .................................... 45
4.4 Comments ............................................ 45
4.5 Compiler Directives ..................................... 46
5.
5.1
5.2
5.2.1
5.2.2
5.2.3
5.2.4
5.2.5
5.3
II
PROGRAM HEADING AND PROGRAM BLOCK .......•..• 47
Program Heading ....................................... 47
Declaration Part ........................................ 47
Label Declaration Part ................................. 48
Constant Definition Part ................................ 48
Type Definition Part ................................... 49
Variable Declaration Part ............................... 49
Procedure and Function Declaration Part ................... 50
Statement Part ........................................ 50
TURBO Pascal Language Manual
6. EXPRESSIONS ....................................... 51
6.1 Operators ............................................. 51
6.1.1 Unary Minus ......................................... 51
6.1.2 Not Operator ......................................... 52
6.1.3 MUltiplying Operators .................................. 52
6.1.4 Adding Operators ..................................... 53
6.1.5 RelationaIOperators ................................... 53
6.2 Function Designators .................................... 54
7. STATEMENTS ........................................ 55
Simple Statements ..................................... 55 7.1
7.1.1
7.1.2
7.1.3
7.1.4
7.2
7.2.1
7.2.2
7.2.2.1
7.2.2.2
7.2.3
7.2.3.1
7.2.3.2
7.2.3.3
Assignment Statement .................................. 55
Procedure Statement .................................. 56
Goto Statement ...................................... 56
Empty Statement ..................................... 56
Structured Statements .................................. 57
Compound Statement .................................. 57
Conditional Statements ................................ 57
If Statement ........................................ 57
Case Statement ..................................... 58
Repetitive Statements ................................. 59
For Statement ...................................... 60
While statement .................................... 61
Repeat Statement ................................... 61
8. SCALAR AND SUBRANGE TYPES ....................... 63
8.1 Scalar Type ........................................... 63
8.2 Subrange Type ......................................... 64
8.3 Type Conversion ....................................... 65
8.4 Range Checking ........................................ 65
9. STRING TYPE ......................................... 67
9.1
9.2
9.3
9.4
9.4.1
9.4.2
9.4.3
9.4.4
String Type Definition ................................... 67
String Expressions ...................................... 67
String Assignment ...................................... 68
String Procedures ...................................... 69
Delete .............................................. 69
Insert .............................................. 69
Str ................................................. 70
Val ................................................ 70
TABLE OF CONTENTS III
9.5 String Functions ....................................... 71
9.5.1 Copy ............................................... 71
9.5.2 Con cat ........ ' ..................................... 71
9.5.3 Length ............................................. 72
9.5.4 Pos ................................................ 72
9.6 Strings and Characters .................................. 73
10. ARRAY TYPE ......................................... 75
10.1 Array Definition ....................................... 75
10.2 Multidimensional Arrays ................................ 76
10.3 Character Arrays ...................................... 77
10.4 Predefined Arrays ..................................... 77
11. ReCORD TYPE ...........................•........... 79
11.1 Record Definition ...................................... 79
11.2 With Statement ....................................... 81
11.3 Variant Records ....................................... 82
12. SETTYPE .............••............................. 85
12.1 Set Type Definition .................................... 85
12.2 Set Expressions ....................................... 86
12.2.1 Set Constructors ..................................... 86
12.2.2 Set Operators ....................................... 87
12.3 Set Assignments ...................................... 88
13. TYPED CONSTANTS .........•.........•........•.•... 89
13.1 Unstructured Typed Constants ........................... 89
13.2 Structured Typed Constants ............................. 90
13.2.1 Array Constants ..................................... 90
13.2.2 Multidimensional Array Constants ....................... 91
13.2.3 Record Constants .................................... 91
13.2.4 Set Constants ....................................... 92
14. FILE TYPES .................•..........••.......••... 93
14.1
14.2
14.2.1
14.2.2
14.2.3
14.2.4
14.2.5
14.2.6
14.2.7
14.2.8
IV
File Type Definition .................................... 93
Operations on Files .................................... 94
Assign ............................................. 94
Rewrite ............................................ 94
Reset ............................................. 94
Read ......................... , ............•........ 95
Write .............................................. 95
Seek .............................................. 95
Flush .............................................. 95
Close .............................................. 96
TURBO Pascal Language Manual
14.2.9 Erase .............................................. 96
14.2.10 Rename ........................................... 96
14.3 File Standard Functions ................................. 97
14.3.1 EOF ............................................... 97
14.3.2 FilePos ............................................ 97
14.3.3 FileSize ............................................ 97
14.4 Using Files ........................................... 97
14.5 Text Files ........................................... 100
14.5.1 OperationsonTextFiles .............................. 100
14.5.2 Logical Devices ..................................... 102
14.5.3 Standard Files ...................................... 103
14.6 Text File Input and Output .............................. 106
14.6.1 Read Procedure .................................... 106
14.6.2 Readln Procedure ................................... 108
14.6.3 Write Procedure .................................... 109
14.6.4 Writeln Procedure ................................... 111
14.7 Untyped Files ........................................ 112
14.7.1 BlockRead / BlockWrite .............................. 112
14.8 I/O checking ........................................ 114
15. POINTER TYPES . .................................... 115
15.1 Defining a Pointer Variable ............................. 115
15.2 Allocating Variables (New) ............................. 116
15.3 Mark and Release .................................... 116
15.4 Using Pointers ....................................... 117
15.5 Space Allocation ...................................... 119
16. PROCEDURES AND FUNCTIONS ...................... 121
16.1 Parameters .......................................... 121
16.1.1 Relaxations on Parameter Type Checking ................. 123
16.1.2 Untyped Variable Parameters .......................... 123
16.2 Procedures .......................................... 125
16.2.1 Procedure Declaration ............................... 125
16.2.2 Standard Procedures ................................ 127
16.2.2.1 ClrEol ........................................... 127
16.2.2.2 ClrScr ........................................... 127
16.2.2.3 Crtlnit .......................................... 127
16.2.2.4 CrtExit .......................................... 128
16.2.2.5 Delay ........................................... 128
16.2.2.6 DelUne ......................................... 128
16.2.2.7 InsLine .......................................... 128
16.2.2.8 GotoXY ......................................... 128
16.2.2.9 LowVideo ....................................... 129
16.2.2.10 NormVideo ..................................... 129
TABLE OF CONTENTS v
16.2.2.11 Randomize ...................................... 129
16.2.2.12 Move .. · ........................................ 129
16.2.2.13 FiIiChar ......................................... 129
16.3 Functions ........................................... 130
16.3.1 Function Declaration ................................. 130
16.3.2 Standard Functions ................................. 132
16.3.2.1 Arithmetic Functions ............................... 132
16.3.2.1.1 Abs ........................................... 132
16.3.2.1.2 ArcTan ........................................ 132
16.3.2.1.3 Cos .................................... ; ...... 132
16.3.2.1.4 Exp ........................................... 133
16.3.2.1.5 Frac ........................................... 133
16.3.2.1.6 Int ............................................ 133
16.3.2.1.7 Ln ............................................ 133
16.3.2.1.8 Sin ........................................... 133
16.3.2.1.9 Sqr ........................................... 134
16.3.2.1.10 Sqrt .......................................... 134
16.3.2.2 Scalar Functions .................................. 134
16.3.2.2.1 Pred .......................................... 134
16.3.2.2.2 Succ .......................................... 134
16.3.2.2.3 Odd ........................................... 134
16.3.2.3 Transfer Functions .................................. 135
16.3.2.3.1 Chr ........................................... 135
16.3.2.3.2 Ord ........................................... 135
16.3.2.3.3 Round ......................................... 135
16.3.2.3.4 Trunc ......................................... 135
16.3.2.4 Miscellaneous Standard Functions .................... 136
16.3.2.4.1 Hi ............................................ 136
16.3.2.4.2 KeyPressed ..................................... 136
16.3.2.4.3 Lo ............................................ 136
16.3.2.4.4 Random ....................................... 136
16.3.2.4.5 Random(Num") .................................. 136
16.3.2.4.6 SizeOf ......................................... 137
16.3.2.4.7 Swap ......................................... 137
16.3.2.4.8 UpCase ........................................ 137
16.4 Forward References ................................... 138
17. INCLUDING FILES ................................... 141
VI TURBO Pascal Language Manual
A.
A.l
A.l.l
A.l.2
A.l.3
A.l.4
A.2
A.3
A.4
A.5
A.5.1
A.5.2
A.6
A.7
A.8
A.8.1
A.8.2
A.S
A.l0
A.ll
CP/M-SO ............................................ 143
compiler Options ...................................... 143
Memory / Com file / cHn-file ........................... 143
Start Address ....................................... 144
End Address ........................................ 145
Find Runtime Error ................................... 145
Standard Identifiers .................................... 146
Absolute Variables ..................................... 146
Addr Function ........................................ 147
Predefined Arrays ..................................... 147
MemArray ......................................... 147
Port Array .......................................... 1 48
Array Subscript Optimization ............................. 148
With Statements ...................................... 148
Pointer Related Items .................................. 148
MemAvail .......................................... 148
Pointers and Integers ................................. 149
External Subprograms .................................. 149
Chain and Execute .................................... 149
In-line Machine Code ................................. 152
CP/M Function Calls .................................. 153 A.12
A.12.1
A.12.2
A.12.3
A.12.4
A.13
A.14
A.15
A.15.1
A.15.1.1
A.15.1.2
A.15.1.3
A.15.1.4
A.15.1.5
A.15.1.6
A.15.2
A.15.2.1
A.15.2.2
A.15.2.3
A.15.2.3.1
Bdos procedure and function .......................... 1 53
BdosH L function .................................... 153
Bios procedure and function ........................... 154
BiosHL function .................................... 154
UserWritten I/O Drivers ............................... 155
Interrupt Handling .................................... 156
Internal Data Formats ................................. 157
Basic Data Types ................................... 157
Scalars .......................................... 1 57
Reals ........................................... 157
Strings .......................................... 158
Sets ............................................ 158
File Interface Blocks ............................... 159
Pointers ......................................... 160
Data Structures .................................... 161
Arrays .......................................... 161
Records ......................................... 161
Disk Files ........................................ 162
Random Access Files ............................. 162
TABLE OF CONTENTS VII
A.15.2.3.2 Text Files ...................................... 162
A.15.3 Parameters ........................................ 162
A.15.3.1 Variable Parameters ............................... 163
A.15.3.2 Value Parameters ................................. 163
A.15.3.2.1 Scalars ........................................ 163
A.15.3.2.2 Reals ......................................... 163
A.15.3.2.3 Strings ........................................ 164
A.15.3.2.4 Sets .......................................... 164
A.15.3.2.5 Pointers ....................................... 164
A.15.3.2.6 Arrays and Records .............................. 165
A.15.4 Function Results .................................... 165
A.16 MemoryManagement ................................. 166
A.16.1 Memory Maps .........•........................... 166
A.16.1.1 Compilation in Memory ............................. 166
A.16.1.2 Compilation To Disk ............................... 167
A.16.1.3 Exeq..Jtion in Memory ............................... 167
A.16.1.4 Execution of A Program File ......................... 168
A.16.2 The Heap and The Stacks ............................. 170
B. MS-DOS/PC-DOS and CP/M-86 ...................... . 173
Common features ..................................... 173 B.1
B.1.1
B.1.1.1
B.1.1.2
B.1.1.3
B.1.1.4
B.1.1.5
B.1.1.6
B.1.2
B.1.3
B.1.4
B.1.4.1
B.1.4.2
B.1.4.3
B.1.4.4
B.1.4.5
B.1.4.6
B.1.5
B.1.5.1
B.1.5.2
B.1.6
B.1.7
B.1.7.1
B.1.7.2
Compiler Options .................................... 173
Memory / Com file / cHn-file .......................... 174
Minimum Code Segment Size ......................... 175
Minimum Data Segment Size ......................... 175
Minimum Free Dynamic Memory ...................... 175
Maximum Free Dynamic Memory ...................... 176
Find Runtime Error " ................................ 176
Standard Identifiers .................................. 177
Absolute Variables ................................... 177
Absolute Address Functions ............................ 178
Addr ............................................. 178
Ofs .............................................. 178
Seg ............................................. 178
Cseg ............................................ 178
Dseg ............................................ 179
Sseg ............................................ 179
Predefined Arrays .................................... 179
Mem Array ........................................ 179
Port Array ........................................ 180
With Statements .................................... 180
Pointer Related Items ................................. 180
MemAvaii ........................................ 180
Pointer Values ..................................... 180
VIII TURBO Pascal Language Manual
8.1.7.2.1 AssigningaValuetoaPointer ....................... 181
8.1.7.2.2 ObtainingTheValueofa Pointer ..................... 181
8.1.8 External Subprograms ................................ 181
8.1.9 Chain and Execute ................................... 182
8.1.10 In-line Machine Code ................................ 184
8.1.11 Interrupt Handling ................................... 186
8.1.11.1 Intrprocedure .................................... 186
8.1.12 Internal Data Formats ................................ 187
8.1.12.1 8asicDataTypes .................................. 187
8.1.12.1.1 Scalars ........................................ 187
8.1.12.1.2 Reals .......................................... 188
8.1.12.1.3 Strings ........................................ 188
8.1.12.1.4 Sets .......................................... 189
8.1.12.1.5 Pointers ....................................... 189
8.1.12.2 DataStructures ................................... 189
8.1.12.2.1 Arrays ......................................... 190
8.1.12.2.2 Records ....................................... 190
8.1.12.2.3 Disk Files ...................................... 190
8.1.12.2.4 TextFiles ...................................... 191
8.1.12.3 Parameters ...................................... 191
8.1.12.3.1 Variable Parameters .............................. 192
8.1.12.3.2 Value Parameters ................................ 192
8.1.12.3.2.1 Scalars ....................................... 193
8.1.12.3.2.2 Reals ........................................ 193
8.1.12.3.2.3 Strings ....................................... 193
8.1.12.3.2.4 Sets ......................................... 193
8.1.12.3.2.5 Pointers ...................................... 193
8.1.12.3.2.6 Arrays and Records ............................. 193
8.1.12.4 Function Results .................................. 194
8.1.12.5 TheHeapandTheStacks ........................... 194
8.2 The MS-DOS / PC-DOS Implementations .................. 196
8.2.1 Standard Identifiers .................................. 196
8.2.2 Function Calls ....................................... 196
8.2.3 UserWritten I/O Drivers ............................... 196
8.2.4 File Interface 810cks .................................. 198
8.2.5 Random Access Files ................................. 199
8.2.6 Operations on Files ................................... 200
8.2.6.1 Extended File Size .................................. 200
8.2.6.2 File of 8yte ....................................... 200
8.2.6.3 Flush Procedure ................................... 200
TABLE OF CONTENTS IX
B.3 The CP/M-B6 Implementation ........................... 201
B.3.1 Standard Identifiers .................................. 201
B.3.2 Function Calls ....................................... 201
B.3.3 User Written I/O Drivers ............................... 201
B.3A File Interface Blocks .................................. 202
B.3.5 Random Access Files ................................. 204
C. SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS
......................................................... 205
C.1 Input/Output Procedures and Functions .................... 205
C.2 Arithmetic Functions ................................... 206
C.3 Scalar Functions ...................................... 206
CA Transfer Functions ..................................... 206
C.5 String Procedures and Functions .......................... 207
C.6 File handling routines .................................. 207
C.7 Heap Control Procedures and Functions .................... 20B
C.B Screen Related Procedures ............................... 20B
C.9 Miscellaneous Procedures and Functions ................... 20B
D. SUMMARY OF OPERATORS ........•.•............... 211
E. SUMMARY OF COMPILER DIRECTiVES ................ 213
E.1 Common Compiler Directives ............................ 214
E.1.1 B -I/O Mode Selection ................................ 214
E.1.2 C - Control Sand C ................................... 214
E.1.3 I -I/O Error Handling ................................. 214
E.l.4 I-Include Files ...................................... 214
E.1.5 R-lndexRangeCheck ................................ 215
E.1.6 V - Var-parameter Type Checking ........................ 21 5
E.1.7 U - User Interrupt .................................... 21 5
E.2 CP/M-BO Compiler Directives ............................ 216
E.2.1 A - Absolute Code .................................... 216
E.2.2 W - Nesting of With Statements ........................ 216
E.2.3 X -Array Optimization ................................ 216
E.3 CP/M-B6/ MS-DOS / PC-DOS Compiler Directives ........... 217
E.3.1 K - Stack Checking ................................... 217
F. TURBO VS. STANDARD PASCAL ...................... 219
F.1 DynamicVariables ................. " .................... 219
F.2 Recursion ............................................ 219
F.3 GetandPut .......................................... 219
FA Goto Statements ...................................... 220
F.5 Page Procedure ....................................... 220
F.6 Packed Variables ...................................... 220
F.7 Procedural Parameters .................................. 220
X TURBO Pascal Language Manual
G. COMPILER ERROR MESSAGES ....................... 221
H. RUN-TIME ERROR MESSAGES ....................... 225
I. I/O ERROR MESSAGES ............................... 227
J. TRANSLATING ERROR MESSAGES .................... 229
J.1 Error Message File Listing ............................... 230
K. TURBO SyNTAX ..................................... 233
L. ASCII TABLE ........................................ 239
M. HELP!!! ............................................ 241
N. TERMINAL INSTALLATION ........................... 243
N.1 IBM PC Display Selection ............................... 243
N.2 Non-IBM PC Installation ................................ 244
O. SUBJECT INDEX. ..................................... 249
XI TURBO Pascal Language Manual
lOST OlF lFDGURES
1 -1 Structure of Manual ...................................... 3
1-1 Log-on Message ......................................... 7
1-2 Main Menu ............................................. 7
1-3 Installation Main Menu .................................... 8
1-4 Main Menu ............................................ 13
1 -5 Editor Status Line ....................................... 18
A-1 Options Menu ........................................ 143
A-2 Start and End Addresses ................................ 144
A-3 Run-time Error Message ................................ 145
A-4 Find Run-time Error .................................... 146
A-5 Memory map during compilation in memory ................. 166
A-6 Memory map during compilation to a file ................... 167
A-7 Memory map during execution in direct mode ................ 168
A-8 Memory map during execution of a program file .............. 169
8-1 Options Menu ........................................ 173
8-2 Memory Usage Menu .................................. 174
8-3 Run-time Error Message ................................ 176
8-4 Find Run-time Error .................................... 176
N-1 IBM PC Screen Installation Menu ......................... 243
N-2 Terminal Installation Menu .............................. 244
(LOST OlF 1rAl3lLlES
1-1 Editing Command Values ................................. 12
1-2 Editing Command Overview ............................... 20
14-1 Operation of EOLN and Eof ............................. 103
TABLE OF CONTENTS XII
This book is a reference manual for the TURBO Pascal system as implemen-
ted for the CP/M-80, CP/M -86, and MS/DOS operating systems. Although
making thorough use of examples, it is not meant as a Pascal tutorial or text-
book, and at least a basic knowledge of Pascal is assumed.
The Pascal Language
Pascal is a general-purpose, high level programming language originally de-
signed by Professor Niklaus Wirth of the Technical University of Zurich, Swit-
zerland and named in honor of Blaise Pascal, the famous French Seven-
teenth Century philosopher and mathematician.
Professor Wirth's definition of the Pascal language, published in 1971, was
intended to aid the teaching of a systematic approach to computer program-
ming, specifically introducing structured programming. Pascal has since been
used to program almost any task on almost any computer. Pascal is today
established as one of the foremost high-level languages; whether the applica-
tion is education or professional programming.
TU RBO Pascal
TU RBO Pascal is designed to meet, the requirements of all categories of
users: it offers the student a friendly interactive environment which greatly
aids the learning process; and in the hands of a programmer it becomes an
extremely effective development tool providing both compilation and execu-
tion times second to none.
TURBO Pascal closely follows the definition of Standard Pascal as defined by
K. Jensen and N. Wirth in the Pascal User Manual and Report. The few and
minor differences are described in section F . A number of extensions are pro-
vided. Among these are:
Absolute address variables
Bit/byte manipulation
Direct access to CPU memory and data ports
Dynamic strings
Free ordering of sections within declaration part
Full support of operating system facilities
INTRODUCTION 1
In-line machine code generation
I nclude files
Logical operations on integers
Program chaining with common variables
Random access data files
Structured constants
Type conversion functions
In addition, some extra standard procedures and functions are included to
further increase the versatility of TURBO Pascal.
Structure of This Manual
As this manual describes three slightly different TURBO Pascal implementa-
tions, CP/M-BO, CP/M-B6, and MS-DOS/PC-DOS, the reader should keep
the following structure in mind:
1: Chapter 1 describes the installation and use of TURBO Pascal, the built-in
editor, etc. This information applies to all three implementations.
2: The main body of the manual, chapters 2 through 17 , describe the com-
mon parts of TURBO Pascal, i.e. those parts of the language which are
identical in all three versions. These include Standard Pascal and many ex-
tensions. As long as you use the language as described in these chapters,
your programs will be fully portable between implementations.
3: Appendices A and B describe items which have not been covered in pre-
vious chapters because they differ among implementations, e.g. special
features, requirements, and limitations of each implementation. To avoid
confusion, you need only read the one appendix pertaining to your
implementation. These appendices mostly describe the more intricate de-
tails of programming (e.g. direct memory and port accesses, user written
I/O drivers, internal data formats, etc.), and need only be read by those
who wish to use TURBO Pascal to its fullest extent. Remember, however,
that as these things are implementation dependent, programs using them
are no longer directly portable between implementations.
4: The remaining appendices are common to all implementations and contain
summaries of language elements, syntax diagrams, error messages, an
alphabetical subject index, etc.
Appendix M contains some answers to the most common questions - read
them if you have any problems.
2 TURBO Pascal Language Manual
The following is a graphic representation of the manual:
Special features
for 8 -bit systems
Typography
Special features
for 16 -bit systems
Common appendices
Figure 1: Structure of Manual
The body of this manual is printed in normal typeface. Special characters are
used for the following special purposes:
Typewri ter Typewriter-characters are used to illustrate program ex-
amples and screen output. Screen images are furthermore
shown in rectangular fields of thin lines.
Italics Italics are used in general to emphasize sections of the
text. In particular, pre-defined standard identifiers are
printed in italics, and elements in syntax descriptions (see
below) are printed in italics. The meaning of the use of ita-
lics thus depends on the context.
Boldface Boldface is used to mark reserved words; in the text as
well as in program examples.
INTRODUCTION 3
Margins Certain sections, like this one, are printed in smaller type and with an
extra wide margin. This indicates that their contents is of a less impor-
tant nature than the surrounding text, and that they may therefore be
skipped on a first reading of this manual.
Syntax Descriptions
The entire syntax of the Pascal language expressed as Backus-Naur Forms is
collected in in appendix K which also describes the typography and special
symbols used in these forms.
Where appropriate syntax desctiptions are also used more specifically to
show the syntax of single language elements as in the following syntax desc-
ription of the function Concat:
Concat (Sa, St2 { , StN} )
Reserved words are printed in boldface, standard identifiers use mixed upper
and lower case, and elements explained in the text are printed in italics.
The text will explain that St1, St2, and StN must be string expressions. The
syntax description shows that the word Concat must be followed by two or
more string expressions, separated by commas and enclosed in parentheses.
In other words, the following examples are legal (assuming that Name is a
string variable):
4
ConcatC'TORBO',' Pascal')
Concat C 'TIT' , 'RID' " Pascal')
ConcatC 'T', 'U', 'R', 'B', '0' ,Name)
TURBO Pascal Language Manual
USING THE TURBO SYSTEM
1). lUJSU rnG 1fIHJ[E 1r{UHRlBO SYSTEM
This chapter describes the installation and use of the TURBO Pascal system.
specifically the built-in editor.
1.1 .COM and .CMD files
Files with the extension .COM mark the executable program files in CP/M -80
and MS-DOS / PC-DOS. In CP/M-86 these will instead be marked .CMD.
Thus. whenever .COM -files are mentioned in the following. it should be un-
derstood as .CMD if your operating system is CP/M-86.
1.2 BEFORE USE
Before using the TURBO Pascal you should. for your own protection. make a
work-copy of the distribution diskette and store the original safely away. Re-
member that the User's License allows you to make as many copies as you
need for your own personal use and for backup purposes only. Use a file-
copy program to make the copy. and make sure that all files are successfully
transferred.
1.3 Compiler Directive Defaults
TURBO Pascal provides a number of compiler directives to control
special runtime facilities like e.g. indol( checl(ing, recursion (CP/m-SO
only), etc. PLEASE NOTICE that the default settings of these directi-
ves will optimize ol(ecution speed and minimize code size. Thus, a
number of runtime facilities (such as indox checking and recursion)
are de-selected until explicitly selectod by the programmer. All com-
piler directives and their default values are described in appendix E .
USING THE TURBO SYSTEM 5
1.4 Files On The Distribution Disk
1.4 Files On The Distribution Disk
The distribution disk contains the following files:
TURBO.COM
TURBO.OVR
TURBO.MSG
TLlST.COM
TINST.COM
TINST.DTA
TINST.MSG
. PAS files
READ.ME
The TURBO Pascal program. When you enter the
command TURBO on your terminal, this file will load, and
the program will be up and running.
Overlay file for TURBO.COM (CP/M-80 version only).
Needs only be present on the run-time disk if you want to
execute .COM files from TURBO.
Text file containing error messages. Needs not be present
on your run-time disk if you will accept the system wit-
hout explanatory compile-time error messages. Errors will
in that case just print out an error number, and the manual
can be consulted to find the explanation. In any case, as
the system will automatically point out the error, you may
find it an advantage to use TURBO without these error
messages; it not only saves space on the disk, but more
importantly, it gives you approx 1.5 Kbytes extra memory
for programs. This message file may be edited if you wish
to translate error messages into another language - more
about that in appendix J
Source text listing program. Needs not be present on run-
time disk.
Installation program. Just type TINST at your terminal,
and the program tnkcs you through a completely menu-
driven installation procedure. This and the following files
need not be present on your run-time disk.
Terminal installation data (not present on IBM PC ver-
sions).
Messages for the installation program. Even this file may
be translated into any language desired.
Sample Pascal programs .
If present, this file contains the latest corrections or sug-
gestions on the use of the system.
Only TURBO. COM must to be on your run-time disk. A fully operative
TURBO Pascal thus requires only 28 K of disk space (33 K for 16-bit sy-
stems). TURBO.OVR is required only if you want to be able to execute pro-
grams from the TURBO menu. TURBO.MSG is needed only if you want on-
line compile-time error messages. TUST.COM is used only to list TURBO pro-
grams on the printer, and finally all TlNST files are used only for the installa-
tion procedure. The example .PAS files, of course, may be included on the
run-time disk if so desired, but are not necessary.
. 6
TURBO Pascal Language Manual
Starting TURBO Pascal 1.5
1.5 Starting TURBO Pascal
When you have a copy of the system on your work-disk, enter the command
TURBO
at your terminal. The system will log on with the following message:
TURBO Pascal release n.rm - [version]
Copyright (C) 1983 by BORLAND International
No terminal selected
Include error messages (Y/N)?D
Figure 1-1: Log-on Message
In the first line, n.nn identifies your release number and [versionJ indicates the
operating environment (operating system and CPU),
e.g. CP/M- 86 on IBM PC PC. The third line tells you which screen is instal-
led. At the mo
ment none - but more about that later.
If you enter a V in response to the question, the error message file will be read
into memory (if it is on the disk), briefly displaying the
message Loading TURBO. MSG. You may instead answer N and save about
1.5 Kbytes of
memory. Then the TURBO main menu will appear:
Logged drive: A
Work file:
Main file:
Edi t Compi Ie Run Save
eXecute Dir Quit compiler Options
Text: G bytes
Free: 62903 bytes
Figure 1-2: Main Menu
USING THE TURBO SYSTEM
7
1.5 Starting TURBO Pascal
The menu shows you the commands available, each of which will be descri-
bed in detail in following sections. Each command is executed by entering the
associated capital letter (highlighted after terminal installation if your terminal
has that feature). Don't press <RETURN), the command executes im-
mediately. The values above for Logged drive and memory use are for the
sake of example only; the values shown will be the actual values for your
computer.
IBM PC users can use TURBO as it comes and may skip the following and go
to section 1.7 . If you're an non-IBM PC user, you may use TURBO without
installation if you don't plan to use the built-in editor - but assuming that you
do, type Q now to leave TURBO for a minute to perform the installation.
1.6 Installation
Type TINST to start the installation program. All TlNST files and the
TURBO. COM file must be on the logged drive. This menu will appear:
TURBO Pascal installation menu.
Choose installation item from the following:
[S]creen installation [C]ommand installation [Q]uit
Enter S, C, or Q:
Figure 1-3: Installation Main Menu
1.6.1 IBM PC Screen Installation
When you hit 5 to perform Screen installation, a menu will appear which lets
you select the sCreen mode you want to use while running TURBO (see ap-
pendix N for details). When you have made your choice, the main menu re-
appears, and you may now continue with the Command installation de-
scribed in section 1.6.3 or you may terminate the installation at this point by
entering Q for Quit.
8
TURBO Pascal Language Manual
Non-IBM PC Screen Installation 1.6.2
1.6.2 Non-IBM PC Screen Installation
Now hit S to select Screen installation. A menu containing the names of the
mostly used terminals will appear, and you may choose the one that suits you
by entering the appropriate number. If your terminal is not on the menu, nor
compatible with any of these (note that a lot of terminals are compatible with
e.g. ADM -3AL then you must perform the installation yourself. This is quite
straightforward, but you will need to consult the manual that came with your
terminal to answer the questions asked by the installation menu. See appen-
dix N for details.
When you have chosen a terminal, you are asked if you want to modify the in-
stallation before installation. This can be used if you have e.g. an ADM -3A
compatible terminal with some additional features. Choose the ADM -3A and
add the required commands to activate the special features. If you answer
Yes, you will be taken through a series of questions as described in appendix
N.
Normally, you will answer No to this question, which means that you are sa-
tisfied with the pre-defined terminal installation. Now you will be asked the
operating frequency of your microprocessor. Enter the appropriate value (2, 4,
6 or 8, most probably 4).
After that, the main menu re-appears, and you may now continue with the
Command installation described in the next section or you may terminate the
installation at this point by entering Q for Quit.
1.6.3 Installation of Editing Commands
The built-in editor responds to a number of commands which are used to
move the cursor around on the screen, delete and insert text, move text etc.
These commands have default values which comply with the 'standard' set by
WordStar, but they may easily be taylored to fit your taste or your keyboard.
When you hit C for Command installation, the first command appears:
CURSOR MOVEMENTS:
1: Character left Ctrl-S ->D
USING THE TURBO SYSTEM 9
1.6.3
Installation of Editing Commands
This tells you that the command to move the cursor one character to the left
is currently a Ctrl-S (Control-S, i.e. hold down the key marked CONTROL or
CTRL and press 5), as in WordStar. If you want to use another command, you
may enter it following the - > in either of two ways:
1) Simply press the key you want to use. It could be a function key (e.g. a
left-arrow-key, if you have it) or any other key or sequence of keys that
you choose (max. 4). The installation program responds with a mnemonic
of each character it receives. If you have a left-arrow-key that transmits an
<ESCAPE> character followed by a lower case a, and you press this key in
the situation above, your screen will look like this:
CURSOR MOVEMENTS:
1: Character left Ctrl-S - > <ESC> a II
2) Instead of pressing the actual key you want to use, you may enter the AS-
CII value(s) of the character(s) in the command. The values of multiple
characters are entered separated by spaces. Decimal values are just ente-
red: 27; hexadecimal values are prefixed by a doliar-sign:$lB. This may be
useful to install commands which are not presently available on your key-
board, e.g. if you want to install the values of a new terminal while still us-
ing the old one. This facility has just been provided for very few and rare
instances, because there is really no idea in defining a command that can-
not be generated by pressing a key. But it's there for those who wish to
use it.
In both cases, terminate your input by pressing <RETURN>.Notice that the
two methods cannot be mixed within one command, i.e. if you have started
defining a command sequence by pressing keys, you must define all charac-
ters in that command by pressing keys and vise versa.
You may enter a - (minus) to remove a command from the list, and a B backs
through the list one item at a time.
10 TURBO Pascal Language Manual
Installation of Editing Commands 1.6.3
The editor accepts a total of 45 commands, and they may all be changed to
your specification. If you make an error in the installation, e.g. define the same
command for two different purposes, an self-explanatory error message is is-
sued, and you must correct the error before terminating the installation. The
following table lists the default value and the use of each command, and
space is allowed for you to mark your changes, if any.
CURSOR MOVEMENTS:
1: Character left Ct r 1- S ->
2: Al ternat ive Ct rl-H ->
3: Character right Ctrl-D ->
4: Word left Ct rl-A ->
5: Word right Ctrl-F ->
6: Line up Ct rl-E ->
7: Line down Ct rl-X ->
8: Scroll up Ctrl-W ->
9: Scroll down Ct rl-Z ->
18: Page up Ctrl-R ->
11: Page down Ctrl-C ->
12: To left on 1 ine Ctrl-Q Ctrl-S ->
13: To right on 1 ine Ctrl-Q Ctrl-D ->
14: To top of page Ctrl-Q Ctrl-E ->
15 : To bottom of page Ctrl-Q Ctrl-L->
16: To top of file Ctrl-Q Ctrl-R ->
17: To end of file Ctrl-Q Ctrl-C ->
18: To beginning of block Ctrl-Q Ctrl-B ->
19: To end of block Ctrl-Q Ctrl-B ->
I
28: To last cursor position Ctrl-Q Ctrl-P ->
INSERT & DELEI'E:
21: Insert mode on/off Ctrl-V ->
22: Insert 1 ine Ctrl-N ->
23: Delete 1 ine Ctrl-Y ->
24: Delete to end of 1 ine Ctrl-Q Ctrl-Y ->
25: Delete right word Ctrl-T ->
26: Delete character under cursor Ctrl-G ->
27: Delete left character <DEL> - >
28: Alternative: Nothing ->
USING THE TURBO SYSTEM 11
1.6.3 Installation of Editing Commands
BLOCK COMMANDS:
29: Mark block begin Ctrl-K Ctrl-B ->
30: Mark block end Ctrl-K Ctrl-K ->
31: Mark single word Ctrl-K Ctrl-T ->
32: Hide/display block Ctrk-K Ctrl-W ->
33: Copy block Ctrl-K Ctrl-C ->
34: Move block Ctrl-K Ctrl-V ->
35: Delete block Ctrl-K Ctrl-Y ->
36: Read block from disk Ctrl-K Ctrl-R ->
37: Write block to disk Ctrl-K Ctrl-W ->
MISC. EDITING COMMANDS:
38: End edit Ctrl-K Ctrl-D
->------
39: Tab Ct rl- I ->
40: Auto tab on/off Ctrl-Q Ctrl-I
->------
41 : Restore line Ctrl-Q Ctrl-L
->------
42: Find Ctrl-Q Ctrl-F
->------
43: Find & replace Ctrl-Q Ctrl-A
->------
44: Repeat last find Ct rl-L ->
45: Control character prefix Ctrl-P ->
Table 1-1 : Editing Command Values
Items 2 and 28 let you define alternative commands to Character Left and
Delete left Character commands. Normally (85) is the alternative to Ctrl-5,
and there is no defined alternative to (DEL>. You may redefine these to suit
your keyboard, e.g. to use the (85) as an alternative to (DEL> if the (85)
key is more conveniently located. Of course, the two alternative commands
must be unambiguous like all other commands.
12 TURBO Pascal Language Manual
The Menu 1.7
1.7 The Menu
After installation, you once again activate TURBO Pascal by typing the com-
mand TURBO. Your screen should now clear and display the menu, this time
with the command letters highlighted. If not, check your installation data.
Logged drive: A
Work file:
l!ain file:
Mit
eXecute
Campi Ie Run
Dir Quit
Text: 0 bytes
Free: 62903 bytes
>D
Save
compiler Options
Figure 1-4: Main Menu
By the way, whenever highlighting is mentioned here, it is naturally assumed
that your screen has different video attributes to show text e.g. in different in-
tensities, inverse, underline or some other way. If not, just disregard any men-
tion of highlighting.
This menu shows you the commands available to you while working with
TURBO Pascal. A command is activated by pressing the associated upper
case (highlighted) letter. Don't press (RETURN), the command is executed
immediately. The menu may very well disappear from the screen when work-
ing with the system; it is easily restored by entering an 'illegal command', i.e.
any key that does not activate a command. (RETURN) or (SPACE) will do
perfectly.
The following sections describe each command in detail.
USING THE TURBO SYSTEM 13
1.7.1 Logged Drive Selection
1 .7.1 Logged Drive Selection
The L command is used to change the currently logged drive. When entering
an L, the following prompt is issued:
New drive: •
inviting you to enter a drive name, i.e. a letter from A through P, optionally fol-
lowed by a colon and terminated with (RETURN). If you don't want to
change the current value, just hit (RETURN). The L command performs a
disk-reset, even when you don't change the drive, and should therefore be
used whenever you change disks to avoid a fatal disk write error (CP/M only!).
The new drive is not immediately shown on the menu, as it is not automati-
cally updated. Hit e.g. (SPACE) to display a fresh menu which will show the
new logged drive.
1 .7.2 Work File Selection
The W command is used to select a work file, i.e. the file to be used to Edit,
Compile, Run, eXecute, and Save. The W command will issue this com-
mand:
Work f i Ie name: II
and you may respond with any legal file name, i.e. a name of one through
eight characters, an optional period, and an optional file type of no more than
three characters:
FILENAME. TYP
If you enter a file name without period and file type, the file type PAS is auto-
matically assumed and appended to the name. You may explicitly specify a
file name with no file type by entering a period after the name, but omitting
the type.
Examples:
P.RCGRAM becomesPROGRAM. PAS
PROGRAM. is not changed
PROGRAM. FIL is not changed
File types .BAK, .CHN, and .COM/.CMD should be avoided, as TURBO uses
these names for special purposes.
14
TURBO Pascal Language Manual
Work File Selection 1.7.2
When the Work file has been specified, the file is read from disk, if present. If
the file does not already exist, the message New Fi Ie is issued. If you have
edited another file which you have not saved, the message:
Workfile X:FlLENAME.TYP not saved. Save (Y/N)?D
warns you that you are about to load a new file into memory and overwrite
the one you have just worked on. Answer V to save or N to skip.
The new work file name will show on the menu the next time it is updated,
e.g. when you hit (SPACE).
1.7.3 Main Rle Selection
The M command may be used to define a main file when working with
programs which use the compiler directive $1 to include a file. The Main
file should be the file which must start the compilation, i.e. the file which
contains the include directives. You can then define the Work file to be
different from the Main file, and thus edit different include files while
leaving the name of the Main file unchanged.
When a compilation is started, and the Work file is different from the
Main file, the current Work file is automatically saved, and the Main file
is loaded into memory. If an error is found during compilation, the file
containing the error (whether it is the Main file or an include file) auto-
matically becomes the Work file which may then be edited. When the
error has been corrected and compilation is started again, the corrected
Work file is automatically saved, and the Main file is re-Ioaded.
The Main file name is specified as described for the Work file name in
the previous section.
USING THE TURBO SYSTEM 15
1.7.4 Edit Command
1.7.4 Edit Command
The E command is used to invoke the built-in editor and edit the file defined
as the Work file. If no Work file is specified, you are first asked to specify one.
The menu disappears, and the editor is activated. More about the use of the
editor in section 1 .8 .
While you may use the TURBO system to compile and run programs without
installing a terminal, the use of the editor requires that your terminal be instal-
led. See section 1 .6 .
1.7.5 Compile Command
The C command is used to activate the compiler. If no Main file is specified,
the Work file will be compiled, otherwise the Main file will be compiled. In the
latter case, if the Work file has been edited, you will be asked whether or not
to save it before the Main file is loaded and compiled. The compilation may be
interrupted at any moment by pressing a key.
The compilation may result either in a program residing in memory, in a .COM
file, or in a .CHN file. The choice is made on the compiler Options menu de-
scribed in sections A.1 (8 bit systems) and B.1.1 (16 bit systems). The default
is to have the program residing in memory.
; .7.6 Run Command
The R command is used to activate a program residing in memory or, if the C-
switch on the compiler Options menu is active, a TURBO object code file (.-
COM or .CMD file). If a compiled program is already in memory, it will be acti-
vated. If not, a compilation will automatically take place following the rules
above.
1.7.7 Save Command
The S command is used to save the current Work file on disk. The old version
of this file, if any, will be renamed to .BAK, and the new version will be saved.
16 TURBO Pascal Language Manual
eXecute Command 1.7.8
1.7.8 eXecute Command
The X command lets you run other programs from within TURBO Pas-
cal, e.g. copying programs, word processors - in fact anything that you
can run from your operating system. When entering X, you are promp-
ted:
Command: 0
You may now enter the name of uny program which will then load and
run normally. Upon exit from the program, control is re-transferred to
TURBO Pascal, and you return to the TURBO prompt> .
1.7.9 Directory Command
The D command gives you a directory listing and information about remaining
space on the logged drive. When hitting D, you are prompted thus:
Dir mask: 0
You may enter a drive designator or a drive designator followed by a file name
or a mask containing the usual wildcards * and? . Or you may just hit
<RETURN) to get a full directory listing.
1.7.10 Quit Command
The Quit command is used to leave the TURBO system. If the Work file has
been edited since it was loaded, you are asked whether you want to save it
before quitting.
1.7.11 compiler Options
The 0 command selects a menu on which you may view and change
some default values of the compiler. It also provides a helpful function
to find run-time errors in programs compiled into object code files.
As these options vary between implementations, further discussion is
deferred to appendices A and B .
USING THE TURBO SYSTEM 17
1.8 The TURBO Editor
1.8 The TURBO Editor
The built-in editor is a screen-editor specifically designed for the creation of
program text. If you are familiar with MicroPro's WordStar, you will need no
further instruction in the use of the TURBO editor, as the standard definition
of all commands are exactly like the ones you know from WordStar. There are
a few minor diferencies, and the TURBO editor has a few extensions; these
are discussed in section 1.9.
Using the TURBO editor is simple as can be: when you have defined a Work
file and hit E, the menu disappears, and the editor is activated. If the Work file
exists on the drive, it is loaded and the first page of text is displayed. If it is a
new file, the screen is blank apart from the status line at the top.
Text is entered on the keyboard just as if you were using a typewriter. To ter-
minate a line, press the <RETURN) key (or CR or ENTER or whatever it is cal-
led on your keyboard). When you have entered enough lines to fill the screen,
the top line will scroll off the screen, but don't worry, it is not lost, and you
may page back and forth in your text with the editing commands described la-
ter.
Let us first take a look at the meaning of the status line at the top of the
screen.
1.8.1 The Status Une
The top line on the screen is the status line containing the following informa-
tion:
Line n
Line n
Coin
18
Col n Insert Indent X:FILmAME.TYP
Figure 1-5: Editor Status Line
Shows the number of the line containing the cursor counted
from the start of the file.
Shows the number of the column containing the cursor coun-
ted from the left side of the screen.
TURBO Pascal Language Manual
The Status line 1.8.1
Insert Indicates that characters entered on the keyboard will be
inserted at the cursor position, i.e. that existing text to the
right of the cursor will move to the right as you write new
text. Using the insert mode on/off command (Ctrl-V by
default) will instead display the text Overwrite. Text entered
on the keyboard will then overwrite characters under the
cursor instead of inserting them.
Indent Indicates that auto-indentation is in effect. It may be switch-
ed off by the auto-indent on/off command (Ctrl-Q Ctrl-I by
default).
X:FILENAME.TVP
The drive, name, and type of the file being edited.
1.8.2 Editing Commands
As mentioned before, text is written as if you were using a typewriter, but as
this is a computerized text editor, it offers you a number of editing facilities
which make text manipulation, and in this case specifically program writing,
much easier than on paper.
The TURBO editor accepts a total of 45 editing commands to move the cur-
sor around, page through the text, find and replace text strings, etc, etc. These
commands can be logically grouped into the following four categories:
Cursor movement commands,
I nsert and delete commands,
Block commands, and
Miscellaneous commands
Each of these groups contain logically related commands which will be desc-
ribed separately in following sections. The following table provides an over-
view of the commands available:
USING THE TURBO SYSTEM 19
1.8.2
CURSOR MJVEMENT COMMANDS:
Character left
Character right
Word left
Word right
Line up
Line down
Scroll up
Scroll down
Page up
Page down
INSERT & DELEI'E COMMANDS:
Insert mode on/off
Insert 1 ine
De lete 1 ine
Delete to end of line
BLOCK COMMANDS:
Mark block begin
Mark block end
Mark single word
Copy block
Move block
Delete block
Read block from disk
Write block to disk
Hide/display block
Editing Commands
To top of screen
To top of file
To top of file
To end of file
To left on 1 ine
To right on line
To beginning of block
To end of block
To last cursor position
Delete right word
Delete character under cursor
Delete left character
MISC. EDITING COMMANDS:
End edit
Tab
Auto tab on/off
Restore 1 ine
Find
Find &. replace
Repeat last find
Control character prefix
Table 1-2: Editing Command Overview
In a case like this, the best way of learning is by doing; so start TURBO, spe-
cify one of the demo Pascal programs as Work file, and enter E to Edit. Then
try the commands as you read on.
Hang on, even if you find it a bit hard in the beginning. It is not just by chance
we have chosen to make the TURBO editor WordStar compatible - the logic
of these commands, once learned, quickly become so much a part of you that
the editor virtually turns into an extension of your mind. Take it from one who
has written megabytes worth of text with that editor. Deep in the night this
man/machine synthesis reaches frightening proportions.
20 TURBO Pascal Language Manual
Editing Commands 1.8.2
Each of the following descriptions consists of a heading defining the com-
mand, followed by the default keystrokes used to activate the command, with
room in between to note which keys to use on your terminal, if you use other
keys. If you have arrow keys and dedicated word processing keys (insert, de-
lete, etc.), it might be convenient to use these. Plese refer to section 1.6.3 for
installation details.
The following descriptions of the commands assume the use of the
default Word-Star compatible keystrol<es.
1.B.3 A Note on Control Characters
I
All commands are issued using control characters. A control character is a
special character generated by your keyboard when you hold down the
(CONTROL) (or (CTRL» key on your keyboard and press any key from A
through Z (well, even [, \, ], A, and _ may generate control characters for that
matter).
The (CONTROL> key works like the (SHIFT) key: if you hold down the
(SHIFT) key and press A, you will get a capital A; if you hold down the
(CONTROL> key and press A, you will get a Control-A (Ctrl-A for short).
1.B.4 Before You Start: How To Get Out
The command which takes you out of the editor is described in section 1 .8.8 ,
but you may find it useful to know already now that the Ctrl-K Ctrl-O com-
mand exits the editor and returns you to the menu environment. This com-
mand does not automatically save the file; that must be done with the Save
command from the menu.
1.B.5 Cursor Movement Commands
1.B.5.1 Basic Movement Commands
The most basic thing to learn about an editor is how to move the cursor
around on the screen, The TURBO editor uses a special group of control cha-
racters to do that, namely the control characters A,S, 0, F, E, R, X, and C.
USING THE TURBO SYSTEM 21
1.8.5.1 Basic Movement Commands
Why these? Because they are conveniently located close to the control-key,
so that your left little finger can rest on that while you use the middle and in-
dex fingers to activate the commands. Furthermore, the characters are arran-
ged in such a way on the keyboard as to logically indicate their use. Let's exa-
mine the basic movements: cursor up, down, left, and right:
E
S D
X
These four characters are placed so that it is logical to assume that Ctrl-E mo-
ves the cursor up, Ctrl-X down, Ctrl-S to the left, and Ctrl-D to the right. And
that is exactly what they do. Try to move the cursor around on the screen with
these four commands. If your keyboard has repeating keys, you may just hold
down the control key and one of these four keys, and the cursor will move ra-
pidly across the screen.
Now let us look at some extensions of those movements:
E R
A 'S D F
X C
The location of the Ctrl-R next to the Ctrl-E implies that Ctrl-R moves the cur-
sor up, and so it does, only not one line at the time but a whole page. Simi-
larly, Ctrl-C moves the cursor down one page at a time.
Likewise with Ctrl-A and Ctrl-F: Ctrl-A moves to the left like Ctrl-S, but a
whole word at a time, and Ctrl-F moves one word to the right.
The two last basic movement commands do not move the cursor but scrolls
the entire screen upwards or downwards in the file:
W E R
A S D F
Z X C
Ctrl-W scrolls up in the file (the lines on the screen move down). and Ctrl-Z
scrolls down in the file (the lines on the screen move up).
22 TURBO Pascal Language Manual
Basic Movement Commands 1.8.5.1
Character left Ctrl-S
Moves the cursor one character to the left non-destructively, i.e. without af-
fecting the character there. <BACKSPACE) may be installed to have the
same effect. This command does not work across line breaks, i.e. when the
cursor reaches the left edge of the screen, it stops.
Character right Ctrl-D
Moves the cursor one character to the right non-destructively, i.e. without af-
fecting the character there. This command does not work across line breaks,
i.e. when the cursor reaches the right end of the screen, the text starts scroll-
ing horizontally until the cursor reaches the extreme right of the line, in co-
lumn 128, where it stops.
Word left Ctrl-A
Moves the cursor to the beginning of the word to the left. A word is defined as
a sequence of characters delimited by one of the following characters: Ispacel
< ) , ; . ( ) [ ] A , * + _ /$. This command works across line breaks.
Word right Ctrl-F
Moves the cursor to the beginning of the word to the right. See the definition
of a word above. This command works across line breaks.
Line up Ctrl-E
Moves the cursor to the line above. If the cursor is on the top line, the screen
scrolls down one line.
Line down Ctrl-X
Moves the cursor to the line below. If the cursor is on the second-last line, the
screen scrolls up one line.
Scroll up Ctrl-W
Scrolls 'up' towards the beginning of the file, one line at a time (i.e. the entire
screen scrolls down). The cursor remains on its line until it reaches the bottom
of the screen.
USING THE TURBO SYSTEM 23
1.8.5.1 Basic Movement Commands
Scroll down Ctrl-Z
Scrolls 'down' towards the end of the file, one line at a time (i.e. the entire sc-
reen scrolls up). The cursor remains on its line until it reaches the top of the
screen.
Page up Ctrl-R
Moves the cursor one page up with an overlap of one line, i.e. the cursor mo-
ves one screenful less one line backwards in the text.
Page down Ctrl-C
Moves the cursor one page down with an overlap of one line, i.e. the cursor
moves one screenful less one line forwards in the text.
1.B.5.2 Extended Movement Commands
The commands discussed above will let you move freely around in your pro-
gram text, and they are easy to learn and understand. Try to use them all for a
while and see how natural they feel.
Once you master them, you will probably sometimes want to move more
rapidly. The TURBO editor provides five commands to move rapidly to the ex-
treme ends of lines, to the beginning and end of the text, and to the last cursor
position.
These commands require two characters to be entered: first a Ctrl-Q and
then one of the following control characters: S, D, E, X, R, and C. They repeat
the pattern from before:
E R
S D
X C
i.e. Ctrl-O Ctrl-S moves the cursor to the extreme left of the line, and. Ctrl-Q
Ctrl-D moves it to the extreme right of the line. Ctrl-Q Ctrl-E moves the cursor
to the top of the screen, Ctrl-Q Ctrl-X moves it to the bottom of the screen.
Ctrl-O Ctrl-R moves the cursor all the way 'up' to the start of the file, Ctrl-Q
Ctrl-C moves it all the way 'down' to the end of the file.
24 TURBO Pascal Language Manual
Extended Movement Commands 1.8.5.2
To left on line Ctrl-Q Ctrl-S
Moves the cursor all the way to the left edge of the screen, i.e. to column one.
To right on line Ctrl-Q Ctrl-D
Moves the cursor to the end of the line, i.e. to the position following the last
printable character on the line. Trailing blanks are always removed from all li-
nes to preserve space.
To top of screen Ctrl-Q Ctrl-E
Moves the cursor to the top of the screen.
To bottom of screen Ctrl-Q Ctrl-X
Moves the cursor to the bottom of the screen.
To top of file Ctrl-Q Ctrl-R
Moves to the first character of the text.
To end of file Ctrl-Q Ctrl-C
Moves to the last character of the text.
Finally the Ctrl-Q prefix with a B, K, or P control character allows you to jump
far within the file:
To beginning of block Ctrl-Q Ctrl-B
Moves the cursor to the the position of the block begin marker set with Ctrl-K
Ctrl-B (hence the B). The command works even if the block is not displayed
(see hide/display block later). or the block end marker is not set.
To end of block Ctrl-Q Ctrl-K
Moves the cursor to the position of the block end marker set with Ctrl-K Ctrl-
K (hence the K). The command works even if the block is not displayed (see
hide /display block later). or the block begin marker is not set.
USING THE TURBO SYSTEM 25
1.B.5.2 Extended Movement Commands
To last cursor position Ctrl-Q Ctrl-P
Moves to the last position of the cursor (the P being a mnemonic for Posi-
tion). This command is particularly useful to move back to the last position af-
ter a S ave operation or after a find or find/replace operation.
1.8.6 Insert and Delete Commands
These commands let you insert and delete characters, words, and lines. They
can be divided into three groups: one command which controls the text entry
mode (insert or overwrite), a number of simple commands, and one extended
command.
Notice that the TURBO editor provides a 'regret' facility which lets you
'undo' changes as long as you have not left the line. This command (Ctrl-Q
Ctrl-L) is described in section 1.8.8 .
1.B.6.1 Insert or Overwrite?
I nsert mode on/off Ctrl-V
When you enter text, you may choose between two entry modes: Insert and
Overwrite. Insert mode is the default value when the editor is invoked. and it
lets you insert new text into an existing text. The existing text to the right of
the cursor simply moves to the right while you enter the new text.
Overwrite mode may be chosen if you wish to replace old text with new text.
Characters entered then replace existing characters under the cursor.
You switch between these modes with the insert mode on/off command Ctrl-
V, and the current mode is displayed in the status line at the top of the screen.
26 TURBO Pascal Language Manual
Simple Insert IDelete Commands 1.8.6.2
1.8.6.2 Simple Insert/Delete Commands
Delete left character (DELETE)
Moves one character to the left and deletes the character there. Any cha-
racters to the right of the cursor move one position to the left. The (BACK-
SPACE) key which normally backspaces non-destructively like Ctrl-S may be
installed to perform this function if it is more conveniently located on your
keyboard. or if your keyboard lacks a (DELETE) key (sometimes labeled
(DEL), (RUBOUT), or (RUB»). This command works across line breaks, i.e.
you can use it to remove line breaks.
Delete character under cursor Ctrl-G
Deletes the character under the cursor and moves any characters to the right
of the cursor one position to the left. This command does not work across line
breaks.
Delete right word Ctrl-T
Deletes the word to the right of the cursor. A word is defined as a sequence of
characters delimited by one of the following characters: Ispacel ( ) , ; . ( ) [ ] A •
* + - I $. This command works across line breaks, i.e. it may be used to re-
move line breaks.
Insert line Ctrl-N
Inserts a line break at the cursor position. The cursor does not move.
Delete line Ctrl-Y
Deletes the line containing the cursor and moves any lines below one line up.
The cursor moves to the left edge of the screen. No provision exists to restore
a deleted line, so take care!
1.8.6.3 Extended Delete Command
One extended delete command is provided: a command to quickly erase from
the cursor position to the end of the line.
USING THE TURBO SYSTEM 27
1.8.6.3 Extended Delete Command
Delete to end of line Ctrl-Q Ctrl-Y
Deletes all text from the cursor position to the end of the line.
1.8.7 Block Commands
All block commands are extended commands (Le. two characters each in the
standard command definition)' and you may ignore them at first if you feel a
bit dazzled at this point. Later on, when you feel the need to move, delete, or
copy whole chunks of text, you should return to this section.
For the persevering, we'll go on and discuss the use of blocks.
A block of text is simply any amount of text, from a single character to several
pages of text. A block is marked by placing a Begin block marker at the first
character and an End block marker at the last character of the desired portion
of the text. Thus marked, the block may be copied, moved, deleted, and writ-
ten to a file. A command is available to read an external file into the text as a
block, and a special command conveniently marks a single word as a block.
Mark block begin Ctrl-K Ctrl-B
This command marks the beginning of a block. The marker itself is not visible
on the screen, and the block only becomes visibly marked when the End block
marker is set, and then only if the screen is installed to show some sort of
highlighting. But even if the block is not visibly marked, it is internally marked
and may be manipulated.
M ark block end Ctrl-K Ctrl-K
This command marks the end of a block. As above, the marker itself is not vi-
sible on the screen, and the block only becomes visibly marked when the Be-
gin block marker is also set.
Mark single word Ctrl-K Ctrl-T
This command marks a single word as a block, and thus replaces the Begin
block - End block sequence which is a bit clumsy when marking just one
word. If the cursor is placed within a word, then this word will be marked; if
not then the word to the left of the cursor will be marked. A word is defined as
a sequence of characters delimited by one of the following characters: Ispacel
<) , ;. () [ r ' * + - /$.
28 TURBO Pascal Language Manual
Block Commands 1.8.7
H ide/display block Ctrl-K Ctrl-H
This command causes the visual marking of a block (dim text) to be alterna-
tely switched off and on. Block manipulation commands (copy, move, delete,
and write to a file) work only when the block is displayed. Block related cursor
movements (jump to beginning/end of block) work whether the block is hid-
den or displayed.
Copy block Ctrl-K Ctrl-C
This command places a copy of a previously marked block starting at the cur-
sor position. The original block is left unchanged, and the markers are placed
around the new copy of the block. If no block is marked, the command per-
forms no operation, and no error message is issued.
Move block Ctrl-K Ctrl-V
This command moves a previously marked block from its original position to
the cursor position. The block disappears from its original position and the
markers remain around the block at its new position. If no block is marked,
the command performs no operation, and no error message is issued.
Delete block Ctrl-K Ctrl-Y
This command deletes the previously marked block. No provision exists to re-
store a deleted block, so take care!
Read block from disk Ctrl-K Ctrl-R
This command is used to read a file into the current text at the cursor position,
exactly as if it was a block that was moved or copied. The block read in is
marked as a block. When this command is issued, you are prompted for the
name of the file to read. The file specified may be any legal filename. If no file
type is specified, .PAS is automatically assumed: A file without type is speci-
fied as a name followed by a period.
USING THE TURBO SYSTEM 29
1.8.7 Block Commands
Write block to disk Ctrl-K Ctrl-W
This command is used to write a previously marked block to a file. The block
is left unchanged, and the markers remain in place. When this command is is-
sued, you are prompted for the name of the file to write to. If the file specified
already exists, a warning is issued before the existing file is overwritten. If no
block is marked, the command performs no operation, and no error message
is issued.The file specified may be any legal filename. If no file type is speci-
fied, .PAS is automatically assumed. A file without type is specified as a name
followed by a period. Avoid the use offile types .BAK, .CHN, and .COM/.CMD,
as they are used for special purposes by the TURBO system.
1.B.B Miscellaneous Editing Commands
This section collects a number of commands which do not logically fall into
any of the above categories. They are nonetheless important, especially this
first one:
End edit Ctrl-K Ctrl-D
This command ends the edit and returns to the main menu. The editing has
been performed entirely in memory, and any associated disk file is not affec-
ted. Saving the edited file on disk is done explicitly with the Save command
from the main menu or automatically in connection with a compilation or
definition of a new Work file.
Tab Ctrl-I
There are no fixed tab positions in the TURBO editor. Instead, tab positions
are automatically set to the beginning of each word on the line immediately
above the cursor. This provides a very convenient automatic tabbing feature
especially useful in program editing where you often want to line up columns
of related items, e.g. variable declarations and such. Remember that Pascal
allows you to write extremely beautiful source texts -do it, not for the sake of
the purists, but more importantly to keep the program easy to understand,
especially when you return to make changes after some time.
30 TURBO Pascal Language Manual
Miscellaneous Editing Commands 1.8.8
Auto tab on/off Ctrl-Q Ctrl-I
The auto tab feature provides automatic indentation. When active, the inden-
tation of the current line is repeated on each following line, i.e. when you hit
<RETURN), the cursor does not return to column one but to the starting co-
lumn of the line you just terminated. When you want to change the indenta-
tion, use any of the cursor right or left commands to select the new column.
When auto tab is active, the message Indent is displayed in the status line,
and when passive the message is removed. Auto tab is active by default.
Restore line Ctrl-Q Ctrl-L
This command lets you regret changes made to a line as long as you have not
left the line. The line is simply restored to its original contents regardless of
what changes you have made. But only as long as you remain on the line; the
minute you leave it, changes are there to stay. For this reason, the Delete line
(Ctrl-Yl command can regrettably only be regretted, not restored. Some days
you'll find yourself continuously falling asleep on the Ctrl-Y key, with vast
consequences. A good long break usually helps.
Find Ctrl-Q Ctrl-F
The Find command lets you search for any string of up to 30 characters.
When you enter this command, the status line is cleared, and you are promp-
ted for a search string. Enter the string you are looking for and terminate with
<RETURN). The search string may contain any characters, also control char-
acters. Control characters are entered into the search string with the Ctrl-P
prefix: enter e.g. a Ctrl-A by holding down the Control key while pressing first
P, then A. You may thus include a line break in a search string by specifying
Ctrl-M Ctrl-J. Notice that Ctrl-A has a special meaning: it matches any cha-
racter and may be used as a wildcard in search strings.
Search strings may be edited with the Character Left, Character Right, Word
Left, and Word Right commands. Word Right recalls the previous search str-
ing which may then be edited. The search operation may be aborted with the
Abort command (Ctrl-U).
When the search string is specified, you are asked for search options. The fol-
lowing options are available:
USING THE TURBO SYSTEM 31
1.8.8
B
G
n
u
w
Examples:
W
BU
125
Miscellaneous Editing Commands
Search backwards, i.e. search from the current cursor position
towards the beginning of the text.
Global search, i.e. search the entire text, irrespective of the cur-
rent cursor position.
n = any number. Find the n'th occurrence of the search string,
counted from the current cursor position.
Ignore upper/lower case, i.e. regard upper and lower case alpha-
beticals as equal.
Search for whole words only, i.e. skip matching petterns which
are embedded in other words.
search for whole words only, i.e. the search string 'term' will only
match the word 'term', not e.g. the word 'terminal'.
search backwards and ignore upper/lower case, i.e. 'Block' will
match both 'blockhead' and 'BLOCKADE', etc.
Find the 125th occurrence of the search string.
Terminate the list of options (if any) with <RETURN), and the search starts. If
the text contains a target matching the search string, the cursor is positioned
at the end of the target. The search operation may be repeated by the Repeat
last find command (Ctrl-L).
Find and replace Ctrl-Q Ctrl-A
The Find and Replace command lets you search for any string of up to 30
characters and replace it with any other string of up to 30 characters. When
you enter this command, the status line is cleared, and you are prompted for a
search string. Enter the string you are looking for and terminate with <RE-
TURN). The search string may contain any characters, also control char-
acters. Control characters are entered into the search string with the Ctrl-P
prefix: enter e.g. a Ctrl-A by holding down the Control key while pressing first
P, then A. You may thus include a line break in a search string by specifying
Ctrl-M Ctrl-J. Notice that Ctrl-A has a special meaning: it matches any cha-
racter and may be used as a wildcard in search strings.
Search strings may be edited with the Character Left, Character Right, Word
Left, and Word Right commands. Word Right recalls the previous search str-
ing which may then be edited. The search operation may be aborted with the
Abort command (Ctrl-U).
32 TURBO Pascal Language Manual
Miscellaneous Editing Commands 1.8.8
When the search string is specified, you are asked to enter the string to rep-
lace the search string. Enter up to 30 caharcters; control character entry and
editing is performed as above, but Ctrl-A has no special meaning in the rep-
lace string. If you just press <RETURN>, the target will be replaced with noth-
ing, i.e. deleted.
Finally you are prompted for options. The search and replace options are:
B
G
n
N
u
w
Examples:
N10
GWU
Search and replace backwards, i.e. search and replace from the
current cursor position towards the beginning of the text.
Global search and replace, i.e. search and replace in the entire
text, irrespective of the current cursor position.
n = any number. Find and replace n occurrences of the search
string, counted from the current cursor position.
Replace without asking, i.e. do not stop and ask Replace (Y/N)
for each occruurence of the search string.
Ignore upper/lower case, i.e. regard upper and lower case alpha-
beticals as equal.
Search and replace whole words only, i.e. skip matching petterns
which are embedded in other words.
Find the next ten occurrences of the search string and replace
without asking.
Find and replace whole words in the entire text. Ignore upper/lo-
wer case.
Terminate the list of options (if any) with <RETURN>, and the search and rep-
lace starts. Depending on the options specified, the string may be found.
When found (and if the N option is not specified), the cursor is positioned at
the end of the target, and you are asked the question: Replace (YIN)? on
the prompt line at the top of the screen. You may abort
the search and replace operation at this point with the Abort command (Ctrl-
U). The search and replace operation may be repeated by the Repeat last find
command (Ctrl-L).
Repeat last find Ctrl-L
This command repeats the latest Find or Find and replace operation exactly as
if all information had been re-entered.
USING THE TURBO SYSTEM 33
1.8.8 Miscellaneous Editing Commands
Control character prefix Ctrl-P
The TURBO editor allows you to enter control characters into the file by pre-
fixing the desired control character with a Ctrl-P. If you e.g. want to enter a
Ctrl-G into a text string to ring the bell, you must first press Ctrl-P and then
Ctrl-G. Control characters are displayed as low-lighted (or inverse, or what
have you) capital letters.
Abort operation Ctrl-U
The Ctrl-U command lets you abort any command in process whenever it
pauses for input, like when Search and Replace asks Replace YIN?, or during
entry of a search string or a file name (block Read and Write).
1.9 The TURBO editor vs. WordStar
Someone used to WordStar will notice that a few TURBO commands work
slightly different, and although TURBO naturally only contains a subset of
WordStar's commands, it has been necessary to include some commands not
found in WordStar. These differencies are discussed in this section.
1.9.1 Cursor Movement
The cursor movement controls Ctrl-S, 0, E, and X move freely around on the
screen and do not jump to column one on empty lines. This does not mean
that the screen is full of blanks; on the contrary, all trailing blanks are automa-
ticaly deleted. This way of moving the cursor is especially useful e.g. when
matching indented begin - end pairs.
Ctrl-S and Ctrl-D do not work across line breaks. To move from one line to
another you must use Ctrl-E, Ctrl-X, Ctrl-A, or Ctrl-F.
1.9.2 Mark Single Word
Ctrl-K Ctrl-T is used to mark a single word as a block which is more conve-
nient than the two-step process of marking the beginning and the end of the
word separately.
34 TURBO Pascal Language Manual
End Edit 1.9.3
1.9.3 End Edit
The Ctrl-K Ctrl-D command has a different effect than in WordStar. As editing
in TURBO is done entirely in memory, this command does not change the file
on disk. This must be done explicitly with the Save command from the main
menu or automatically in connection with a compilation or definition of a new
Work file. TURBO's Ctrl-K Ctrl-D does not resemble WordStar's Ctrl-K Ctrl-Q
(quit edit) command either, as the changed text is not abandoned; it is left in
memory ready to be Compiled or Saved.
1 .9.4 Line Restore
The Ctrl-Q Ctrl-L command restores a line to its contents before edit as long
as the cursor has not left the line.
1.9.5 Tabulator
No fixed tab settings are provided. Instead, tabs are automatically set to the
start of each word on the line immediately above the cursor.
1.9.6 Auto Indentation
The Ctrl-Q Ctrl-I command switches the auto indentation feature on and off.
USING THE TURBO SYSTEM 35
1.9.6 Auto Indentation
Notes:
36 TURBO Pascal Language Manual
BASIC LANGUAGE ELEMENTS 2
2. BASIC LANGUAGE ELEMENTS
2.1 Basic Symbols
The basic vocabuiary of TURBO Pascal consists of basic symbols divided into
letters, digits, and special symbols:
Letters: A toZ, a to z, and_ (underscore)
Digits: 8 1 2 3 4 5 6 7 8 9
Special s·,mbols: + - * / ~ < > ( )
[]{}., 'u$
No distinction is made between upper and lower case letters. Certain opera-
tors and delimiters are formed using two special symbols:
Assignment operator: : =
Relational operators:< > < = >=
Subrange delimiter: ..
Brackets: (. and.) may be used instead of [ and]
Comments: (* and *) may be used instead of { and}
2.2 Reserved Words
Reserved words are integral parts of TURBO Pascal and cannot be redefined.
Reserved words must thus never be used as user defined identifiers. The re-
served words are:
"* absolute "* external
nil
"* shr
and file not
"* string
array for of then
begin forward or to
case function packed type
const goto procedure until
div if program var
do in record "hi Ie
dOlJIlto
"* inline
repeat with
else label set
"* xor
end mod
"* shl
Throughout this manual, reserved words are written in boldface. The aste-
risks indicate reserved words not defined in standard Pascal.
BASIC LANGUAGE ELEMENTS 37
2.3 Standard Identifiers
2.3 Standard Identifiers
TURBO Pascal defines a number standard identifiers of predefined types,
constants, variables, procedures, and functions. Any of these identifiers may
be redefined but it will mean the loss of the facility offered by that particular
identifier and may lead to confusion. The following standard identifiers are
therefore best left to their special purposes:
ArcTan Delay Ln Rename
Assign Delete Lo Reset
Aux IDF LowVideo Rewri te
AuxlnPtr IDIN Lst Round
AuxOutPtr Erase LstOutPtr Seek
BlockRead Execute Mark Sin
BlockWri te Exp Maxlnt SizeOf
Boolean False Mem Sqr
BufLen Fi lePos MemAvai I Sqrt
Byte FileSize Move Str
Chain Fi llChar New Succ
Char Flush NormVideo Swap
Chr Frac Odd Text
Close GetMem Ord Trm
C I rIDL Got oX'! Output True
C 1 rScr HeapPtr Pi Trunc
Con Hi Port UpCase
ConInPtr IOresul t Pos Usr
ConOutPtr Input Pred UsrlnPtr
Concat InsLine Ptr UsrOutPtr
ConstPtr Insert Random Val
Copy Int Randomize Wri te
Cos Integer Read Wri teln
CrtExi t Kbd Read In
Crtlnit KeyPressed Real
DelLine Length Release
Each TURBO Pascal implementation further contains a number of dedicated
standard identifiers which are listed in appendices A and B .
Throughout this manual, standard identifiers, like all other identifiers (see sec-
tion 4.1 ). are written in a combination of upper and lower case letters. In the
text (as opposed to program examples). they are furthermore printed in italics.
38 TURBO Pascal Language Manual
Delimiters 2.4
2.4 Delimiters
Language elements must be separated by at least one of the following deli-
miters: a blank, an end of line, or a comment.
2.5 Program lines
The maximum length of a program line is 127 characters; any character be-
yond the 127th is ignored by the compiler. For this reason the TURBO editor
allows only 127 characters on a line, but source code prepared with other edi-
tors may use longer lines. If such a text is read into the TURBO editor, line
breaks will be automatically inserted, and a warning is issued.
BASIC LANGUAGE ELEMENTS 39
2.5 Program lines
Notes:
40 TURBO Pascal Language Manual
STANDARD SCALAR TYPES 3
3. STAN IOAIRtD SCAILAIfl TYPES
A data type defines the set of values a variable may assume. Every variable in
a program must be associated with one and only one data type. Although
data types in TURBO Pascal can be quite sophisticated, they are all built from
simple {unstructured) types.
A simple type may either be defined by the programmer (it is then called a
declared scalar type). or be one of the standard scalar types: integer, real,
boolean, char, or byte. The following is a description of these five standard
scalar types.
3.1 Integer
Integers are whole numbers; in TURBO Pascal limited to a range of -32768
through 32767. Integers occupy two bytes in memory.
Overflow of integer arithmetic operations is not detected. Notice in particular
that partial results in integer expressions must be kept within the integer
range. For instance, the expression 1000 * 100 / 50 will not yield 2000, as
the multiplication causes an overflow.
3.2 Byte
The type Byte is a subrange of the type Integer, of the range 0 .. 255. Bytes are
therefore compatible with integers, i.e. whenever a Byte value is expected, an
Integer value may be specified instead and vice versa. Furthermore, Bytes and
Integers may be mixed in expressions and Byte variables may be assigned in-
teger values. A variable of type Byte occupies one byte in memory.
STANDARD SCALAR TYPES 41
3.3 Real
3.3 Real
The range of real numbers is 1 E-38 through 1 E+38 with a mantissa of up to
11 significant digits. Reals occupy 6 bytes in memory.
Overflow during an arithmetic operation involving reals causes the program to
halt, displaying an execution error. An underflow will cause a result of zero.
Although the type real is included as a standard scalar type, the following dif-
ferences between reals and other scalar types should be noticed:
1) The functions Pred and Succ cannot take real arguments.
2) Reals cannot be used in array indexing.
3) Reals cannot be used to define the base type of a set.
4) Reals cannot be used in controlling for and case statements.
5) Subranges of reals are not allowed.
3.4 Boolean
A boolean value can assume either of the logical truth values denoted by the
standard identifiers True and False. These are defined such that False < True.
A Boolean variable occupies one byte in memory.
3.5 Char
A Char value is one character in the ASCII character set. Characters are orde-
red according to their ASCII value, e.g. 'A' < 'S'. The ordinal (ASCII) values of
characters range from 0 to 255. A Char variable occupies one byte in me-
mory.
42 TURBO Pascal Language Manual
USER DEFINED LANGUAGE ELEMENTS 4
4. USER DEFINED LANGUAGE ELEMENTS
4.1 Identifiers
Identifiers are used to denote labels, constants, types, variables, procedures,
and functions. An identifier consists of a letter or underscore followed by any
combination of letters, digits, or underscores. An identifier is limited in length
only by the line length of 127 characters, and all characters are significant.
Examples:
TURBO
square
personLcounted
BirthDate
3rdRoot
Two Words
illegal, starts with a digit
illegal, must not contain a space
As TURBO Pascal does not distinguish between upper and lower case letters,
the use of mixed upper and lower case as in BirthDate has no functional mea-
ning. It is nevertheless encouraged as it leads to more legible identifiers. Ve-
ryLongldentifier is easier to read for the human reader than VERYLONGIDEN-
TlFIER. This mixed mode will be used for all identifiers throughout this ma-
nual.
4.2 Numbers
Numbers are constants of integer type or of real type. Integer constants are
whole numbers expressed in either decimal or hexadecimal notation. Hexade-
cimal constants are identified by being preceeded by a doliar-sign:$ABC is a
hexadecimal constant. The decimal integer range is -32768 through 32767
and the hexadecimal integer range is$OOOO through$FFFF.
Examples:
1
12345
-1
$123
$ABC
$123G
1.2345
illegal, G is not a legal hexadecimal digit
illegal as an integer, contains a decimal part
USER DEFINED LANGUAGE ELEMENTS 43
4.2 Numbers
The range of Real numbers is 1 E-38 through 1 E+38 with a mantissa of up to
11 significant digits. Exponential notation may be used, with the letter E pre-
ceding the scale factor meaning "times ten to the power ot". An integer cons-
tant is allowed anywhere a real constant is allowed. Separators are not allo-
wed within numbers.
Examples:
1.0
1234.5678
-0.012
1E6
2E-5
-1. 2345678901E+12
1 legal, but it is not a real, it is an integer
4.3 Strings
A string constant is a sequence of characters enclosed in single quotes, i.e.:
'This is a string constant '
A single quote may be contained in a string by writing two successive single
quotes. Strings containing only a single character are of the standard type
char. A string is compatible with an array of Char of the same length. All
string constants are compatible with all string types.
Examples:
'TURBO'
'You' '11 see'
,. ,
,
As shown in example 2 and 3, a single quote within a string is written as two
consecutive quotes. The four consecutive single quotes in example 3 thus
constitute a string containing one quote.
The last example - the quotes enclosing no characters, denoting the empty
string - is compatible only with string types.
44 TURBO Pascal Language Manual
Control Characters 4.3.1
4.3.1 Control Characters
TURBO Pascal also allows control characters to be embedded in strings. Two
notations for control characters are supported: 1) The tt symbol followed by
an integer constant in the range 0 .. 255 denotes a character of the corre-
sponding ASCII value, and 2) the symbol followed by a character, denotes
the corresponding control character.
Examples:
u10
u$lB

ASCII 10 dec imal (Line Feed).
ASCII 1B hex (Escape).
Control-G (Bell).
1
Control-L (Form Feed). Notice that lower
case is treated as upper case.
[
Control-[ (Escape).
Sequences of control characters may be concatenated into strings by writing
them without separators between the individual characters::
u13u10


The above strings contain two, three, and four characters, respectively. Con-
trol characters may also be mixed with text strings:
'Waiting for input! Please wake up'
tt27'U '
'This is another line of text '
These three strings contain 37, 3, and 31 characters, respectively.
4.4 Comments
A comment may be inserted anywhere in the program where a delimiter is le-
gal. It is delimited by the curly braces { and}, which may be replaced by the
symbols (* and *).
Examples:
{ThiS is a comment}
(* and so is this *)
USER DEFINED LANGUAGE ELEMENTS 45
4.4 Comments
Curly braces may not be nested within curly braces, and C * .. *) may not be
nested within C * .. *). However, curly braces may nested withinC * .. *)
and vise versa, thus allowing entire sections of source code to be commented
away, even if they contain comments.
4.5 Compiler Directi,:,es
A number of features of the TURBO Pascal compiler are controlled through
compiler directives. A compiler directive is introduced as a comment with a
special syntax which means that whenever a comment is allowed in a pro-
gram, a compiler directive is also allowed.
A compiler directive consists of an opening brace immediately followed by a
dollar-sign immediately followed by one compiler directive letter or a list of
compiler directive letters separated by commas. The syntax of the directive or
directive list depends upon the directive(s) selected. A full description of each
of the compiler directives follow in the relevant sections; and a summary of
compiler directives is located in appendix E .
Examples:
{$1 - }
{$1 INCLUDE. F1L}
{$R- ,B+,V-}
(*$X-*)
Notice that no spaces are allowed before or after the dollar-sign.
46 TURBO Pascal Language Manual
PROGRAM HEADING AND PROGRAM BLOCK
5
S. PROGRAM HEADING AND PROGRAM BLOCK
A Pascal program consists of a program heading followed by a program block.
The program block is further divided into a declaration part, in which all ob-
jects local to the program are defined, and a statement part, which specifies
the actions to be executed upon these objects. Each is described in detail in
the following.
S.1 Program Heading
In TURBO Pascal, the program heading is purely optional and of no signifi-
cance to the program. If present, it gives the program a name, and optionally
lists the parameters through which the program communicates with the envi-
ronment. The list consists of a sequence of identifiers enclosed in pa-
rentheses and separated by commas.
Examples:
program C i rc 1 e s;
program Accountant (Input, Output);
program Wri ter( Input, Printer);
S.2 Declaration Part
The declaration part of a block declares all identifiers to be used within the
statement part of that block (and possibly other blocks within it). The declara-
tion part is divided into five different sections:
1) Label declaration part
2) Constant definition part
3) Type definition part
4) Variable declaration part
5) Procedure and function declaration part
Whereas standard Pascal specifies that each section may only occur zero or
one time, and only in the above order, TURBO Pascal allows each of these
sections to occur any number of times in any order in the declaration part.
PROGRAM HEADING AND PROGRAM BLOCK 47
5.2.1 Label Declaration Part
5.2.1 Label Declaration Part
Any statement in a program may be prefixed with a label, enabling direct
branching to that statement by a goto statement. A label consists of a label
name followed by a colon. Before use, the label must be declared in a label
declaration part. The reserved word label heads this part, and it is followed by
a list of label identifiers separated by commas and terminated by a semi-
colon.
Example:
label 10, error, 999, Quit;
Whereas standard Pascal limits labels to numbers of no more than 4 digits,
TURBO Pascal allows both numbers and identifiers to be used as labels.
5.2.2 Constant Definition Part
The constant definition part introduces identifiers as synonyms for constant
values. The reserved word const heads the constant definition part, and is
followed by a list of constant assignments separated by semi-colons. Each
constant assignment consists of an identifier followed by an equal sign and a
constant. Constants are either strings or numbers as defined in sections 4.2
and 4.3.
Example:
canst
Limi t = 255;
Max = 1024;
PassWord 'SFSAM' ;
CursHome = ~ [ 'V';
The following constants are predefined in TURBO Pascal, i.e. they may be re-
ferenced without previous definition:
Name:
Pi
False
True
Maxint
Type and value:
Real (3.1415926536E+OO).
Boolean (the truth value false).
Boolean (the truth value true).
Integer (32767).
As described in section 13, a constant definition part may also define typed
constants.
48 TURBO Pascal Language Manual
Type Definition Part 5.2.3
5.2.3 Type Definition Part
A data type in Pascal may be either directly described in the variable de-
claration part or referenced by a type identifier. Several standard type identi-
fiers are provided, and the programmer may create his own types through the
use of the type definition. The reserved word type heads the type definition
part, and it is followed by one or more type assignments separated by semi-
colons. Each type assignment consists of a. type identifier followed by an
equal sign and a type.
Example:
type
Number = Integer;
Day = (mon,tues,wed,thur,fri,sat,sun);
List = array[ 1. .10] of Real;
More examples of type definitions are found in subsequent sections.
5.2.4 Variable Declaration Part
Every variable occurring in a program must be declared before use. The de-
claration must textually precede any use of the variable, i.e. the variable must
be 'known' to the compiler before it can be used.
A variable declaration consists of the reserved word var followed by one or
more identifier(s), separated by commas, each followed by a colon and a
type. This creates a new variable of the specified type and associates it with
the specified identifier.
The 'scope' of this identifier is the block in which it is defined, and any block
within that block. Note, however, that any such block within another block
may define another variable using the same identifier. This variable is said to
be local to the block in which it is declared (and any blocks within that block),
and the variable declared on the outer level (the global variable) becomes
inaccessible.
Example:
var
Resul t, Intermediate, SubTotal: Real;
I, J, X, Y: Integer;
Accepted, Val id: Boolean;
Period: Day;
Buffer: a r r ~ [ 0 .. 127] of Byte;
PROGRAM HEADING AND PROGRAM BLOCK 49
5.2.5 Procedure and Function Declaration Part
5.2.5 Procedure and Function Declaration Part
A procedure declaration serves to define a procedure within the current pro-
cedure or program (see section 16.2). A procedure is activated from a proce-
dure statement (see section 7.1.2), and upon completion, program execution
continues with the statement immediately following the calling statement.
A function declaration serves to define a program part which computes and
returns a value (see section 16.3). A function is activated when its designator
is met as part of an expression (see section 6.2).
5.3 Statement Part
The statement part is the last part of a block. It specifies the actions to be ex-
ecuted by the program. The statement part takes the form of a compound
statement followed by a period or a semi-colon. A compound statement con-
sists of the reserved word begin, followed by a list of statements separated
by semicolons, terminated by the reserved word end.
50 TURBO Pascal Language Manual
EXPRESSIONS 6
6. EXPRESSDONS
Expressions are algorithmic constructs specifying rules for the computation of
values. They consist of operands, i.e. variables, constants, and function
designators, combined by means of operators as defined in the following.
This section describes how to form expressions from the standard scalar ty-
pes Integer, Real, Boolean, and Char. Expressions containing declared scalar
types, String types, and Set types are described in sections 8.1, 9.2 , and 12.2
, respectively.
6.1 Operators
Operators fall into five categories, denoted by their order of precedence:
1) Unary minus (minus with one operand only).
2) Not operator,
3) Multiplying I, diy, mod, and, shl, and shr.
4) Adding operators: +, -, or, and xor.
5) Relational operators: =, <>, <, >, < =, > =, and in.
Sequences of operators of the same precendece are evaluated from left to
right. Expressions within parentheses are evaluated first and independently of
preceding or succeeding operators.
If both of the operands of the mUltiplying and adding operators are of type In-
teger, then the result is of type Integer. If one (or both) of the operands is of
type Real, then the result is also of type Real.
6.1.1 Unary Minus
The unary minus denotes a negation of its operand which may be of Real or
Integer types.
EXPRESSIONS 51
6.1.2 Not Operator
6.1.2 Not Operator
The not operator negates (inverses) the logical value of its Boolean operand:
not True
not False
= False
= True
TURBO Pascal also allows the not operator to be applied to an Integer ope-
rand, in which case bitwise negation takes place.
Examples:
not 0 = -1
not -15
not $2345
= 14
=$DCBA
6.1.3 Multiplying Operators
Operator Operation
*
rnul t ipl icat ion
*
rnul t ipl icat ion
*
rnul t ipl icat ion
/
division
/
division
/
division
div Integer division
mod modulus
and ari thmet ic and
and logical and
shl shift left
shr shift right
Examples:
52
12 * 34
123 / 4
123 div 4
12 mod 5
= 408
= 30.75
= 30
=2
True and False = False
12 and 22 =4
2 shl 7 = 256
256 shr 7 = 2
Type of operands Type of resul t
Real
Integer
Real, Integer
Real, Integer
Integer
Real
Integer
Integer
Integer
Boolean
Integer
Integer
Real
Integer
Real
Real
Real
Real
Integer
Integer
Integer
Boolean
Integer
Integer
TURBO Pascal Language Manual
Adding Operators
6.1.4 Adding Operators
Operator Operation
+
+
+
addition
addition
addition
subtraction
subtraction
subtraction
or arithmetic or
or logical or
xor arithmetic xor
xor logical xor
Examples:
123+456
456-123. <:)
True or False
12 or 22
= 579
= 333.0
= True
= 30
True xor False = True
12 xor 22 = 26
6.1.5 Relational Operators
6.1.4
Type of operands Type of result
Real Real
Integer Integer
Real, Integer Real
Real Real
Integer Integer
Real, Integer Real
Integer Integer
Boolean Boolean
Integer Integer
Boolean Boolean
The relational operators work on all standard scalar types: Real, Integer, Boo-
lean, Char, and Byte. Operands of type Integer, Real, and Byte may be mixed.
The type of the result is always Boolean, i.e. True or False.
<>
>
<
>=
<=
Examples:
a = b
a <> b
a > b
a < b
a >= b
a <= b
EXPRESSIONS
equal to
not equal to
greater than
less than
greater than or equal to
less than or equal to
true if a is equal to b.
true if a is not equal to b.
true if a is greater than b.
true if a is less than b.
true if a is greater than or equal to b.
true if a is less than or equal to b.
53
6.2 Function Designators
6.2 F unction Designators
A function designator is a function identifier optionally followed by a pa-
rameter list, which is one or more variables or expressions separated by com-
mas and enclosed in parentheses. The occurrence of a function designator
causes the function with that name to be activated. If the function is not one
of the pre-defined standard functions, it must be declared before activation.
Examples:
Round(PlotPos)
Write In(Pi * (Sqr(R)))
(Max(X,Y) < 25) and (Z > Sqrt(X * y))
Volume(Radius,Height)
54 TURBO Pascal Language Manual
STATEMENTS 7
7. S1rATIEM IE ruTS
The statement part defines the action to be carried out by the program (or
subprogram) as a sequence of statements; each specifying one part of the ac-
tion. In this sense Pascal is a sequential programming language: statements
are executed sequentially in time; never simultaneously. The statement part is
enclosed by the reserved words begin and end and within it, statements are
separated by semi-colons. Statements may be either simple or structured.
7.1 Simple Statements
Simple statements are statements which contain no other statements. These
are the assignment statement, procedure statement, goto statement, and
empty statement.
7.1.1 Assignment Statement
The most fundamental of all statements is the assignment statement. It is
used to specify that a certain value is to be assigned to a certain variable. An
assignment consists of a variable identifier followed by the assignment opera-
tor : = followed by an expression.
Assignment is possible to variables of any type (except files) as long as the
variable (or the function) and the expression are of the same type. As an ex-
ception, if the variable is of type Real, the type of the expression may be Inte-
ger.
Examples:
.Angle := .Angle "* Pi;
AccessOK : = False;
Ent ry : = Answer = PassWord;
SpherVol : = 4 "* Pi "* R "* R;
STATEMENTS 55
7.1.2 Procedure Statement
7.1.2 Procedure Statement
A procedure statement serves to activate a previously defined user-defined
procedure or a pre-defined standard procedure. The statement consists of a
procedure identifier, optionally followed by a parameter list, which is a list of
variables or expressions separated by commas and enclosed in parentheses.
When the procedure statement is encountered during program execution,
control is transferred to the named procedure, and the value of possible para-
meters are transferred to the procedure. When the procedure finishes, pro-
gram execution continues from the statement following the procedure state-
ment.
Examples:
Find(Name,Address);
Sort(Address) ;
Uppe rCas e ( Text) ;
UpdateCustFi le(CustRecord);
7.1.3 Goto Statement
A goto statement consists of the reserved word goto followed by a label
identifier. It serves to transfer further processing to that point in the program
text which is marked by the label. The following rules should be observed
when using goto statements:
1) Before use, labels must be declared. The declaration takes place in a label
declaration in the declaration part of the block in which the label is used.
2) The scope of a label is the block in which it is declared. It is thus not pos-
sible to jump into or out of procedures and functions.
7.1.4 Empty Statement
An 'empty' statement is a statement which consists of no symbols, and which
has no effect. It may occur whenever the syntax of Pascal requires a state-
ment but no action is to take place.
Examples:
begin end.
while Answer <> " do;
repeat until KeyPressed; {wait for any key to be hit}
56 TURBO Pascal Language Manual
Structured Statements 7.2
7.2 Structured Statements
Structured statements are constructs composed of other statements which
are to be executed in sequence (compound statements). conditionally
(conditional statements)' or repeatedly (repetitive statements). The discussion
of the with statement is deferred to section 11.2.
7.2.1 Compound Statement
A compound statement is used if more than one statement is to be executed
in a situation where the Pascal syntax aIJows only one statement to be speci-
fied. It consists of any number of statements separated by semi-colons and
enclosed within the reserved words begin and end, and specifies that the
component statements are to be executed in the sequence in which they are
written.
Example:
if Small> Big then
begin
Tmp : = Small;
Small := Big;
Big := Tmp;
end;
7.2.2 Conditional Statements
A conditional statement selects for execution a single one of its component
statements.
7.2.2.1 If Statement
The if statement specifies that a statement be executed only if a certain con-
dition (Boolean expression) is true. If it is false, then either no statement or
the statement folJowing the reserved word else is to be executed. Notice that
else must not be preceded by a semi-colon.
STATEMENTS 57
7.2.2.1
The syntactic ambiguity arising from the construct:
if expr1 then
if expr2 then
stmt1
else
stmt2
is resolved by interpreting the construct as follows:
ifexpr1 then
begin
if expr2 then
stmtT
else
stmt2
end
If Statement
I.e., the else-clause part belongs generally to the last if statement which has
no else part.
Examples:
if Interest > 25 tben
Usury : = True
else
TakeLoan : = OK;
if (Entry < 0) or (Entry> 100) tben
begin
Write( 'Range is 1 to 100, please re- enter: ,);
Read(Ent ry);
end.;
7.2.2.2 Case Statement
The case statement consists of an expression (the selector) and a list of sta-
tements, each preceded by a case label of the same type as the selector. It
specifies that the one statement be executed whose case label is equal to the
current value of the selector. If none of the case labels contain the value of the
selector, then either no statement is executed, or, optionally, the statements
following the reserved word else are executed. The else clause is an expan-
sion of standard Pascal.
58 TURBO Pascal Language Manual
Case Statement 7.2.2.2
A case label consists of any number of constants or subranges separated by
commas followed by a colon. A subrange is written as two constants sepa-
rated by the subrange delimiter ' .. '. The type of the constants must be the
same as the type of the selector. The statement following the case label is
executed if the value of the selector equals one of the constants or if it lies
within one of the subranges.
Valid selector types are all simple types, i.e. all scalar types except real.
Examples:
case Operator of
'+' :
Result
· -
Answer + Result;
, , .
Result
· -
Answer - Result;
'"*' :
Result
· -
Answer
"* Result;
, /' : Resul t
· -
Answer
/
Result;
end;
case Year of
Min .. 1939: begin
Time . - PreWorldWar2;
Writeln('The world at peace ... ,);
end;
1946 .. Max: begin
else
Time . - PostWorldWar2
Wri te In( 'Bui lding a new world. ' );
end;
Time . = WorldWar2;
Writeln('We are at war');
end;
7.2.3 Repetitive Statements
Repetitive statements specify that certain statements are to be executed re-
peatedly. If the number of repetitions is known beforehand, i.e. before the re-
petitions are started, the for statement is the appropriate construct to express
this situation. Otherwise the while or the repeat statement should be used.
STATEMENTS 59
7.2.3.1 For Statement
7.2.3.1 For Statement
The for statement indicates that the component statement is to be repeated-
ly executed while a progression of values is assigned to a variable which is
called the control variable. The progression can be ascending: to or descend-
ing: downto the final value.
The control variable, the initial value, and the final value must all be of the
same type. Valid types are all simple types, i.e. all scalar types except real.
If the initial value is greater than the final value when using the to clause, or if
the initial value is less than the final value when using the downto clause, the
component statement is not executed at all.
Examples:
for I . = 2 to 100 do if A[ I] > Max then Max . - A[ I] ;
for I .= 1 to NoOfLines do
begin
Readln(Line) ;
if Length(Line) < Limit then ShortLines .- ShortLines + 1
else
LongLines := LongLines + 1
end;
Notice that the component statement of a for statement must not contain as-
signments to the control variable. If the repetition is to be terminated before
the final value is reached, a goto statement must be used, although such
constructs are not recommended - it is better programming practise use a
while or a repeat statement instead.
Upon completion of a for statement, the control variable equals the final va-
lue, unless the loop was not executed at all, in which case no assignment is
made to the control variable.
60 TURBO Pascal Language Manual
While statement 7.2.3.2
7.2.3.2 While statement
The expression controlling the repetition must be of type Boolean. The sta-
tement is repeatedly executed as long as expression is True. If its value is
false at the beginning, the statement is not executed at all.
Examples:
while Size> 1 do Size .- Sqrt(Size);
while ThisMonth do
begin
ThisMonth := CurMonth SampleMonth;
Process;
{process this sample by the Process procedure}
end;
7.2.3.3 Repeat Statement
The expression controlling the repetition must be of type Boolean. The se-
quence of statements between the reserved words repeat and until is execu-
ted repeatedly until the expression becomes true. As opposed to the while
statement, the repeat statement is always executed at least once, as evalua-
tion af the condition takes place at the end of the loop.
Example:
repea.t
Wri tee ~ M , 'De lete thi s item? (YIN)');
Read(Answer) ;
until Up]ase(Answer) in [ 'Y' , 'N'];
STATEMENTS 61
7.2.3.3 Repeat Statement
Notes:
62 TURBO Pascal Language Manual
SCALAR AND SUBRANGE TYPES 8
8. SCALAR AND SUBRANGE TYPES
The basic data types of Pascal are the scalar types. Scalar types constitute a
finite and linear ordered set of values. Although the standard type Real is in-
cluded as a scalar type, it does not conform to this definition. Therefore, Reals
may not always be used in the same context as other scalar types.
8.1 Scalar Type
Apart from the standard scalar types (Integer, Real, Boolean, Char, and Byte),
Pascal supports user defined scalar types, also called declared scalar types.
The definition of a scalar type specifies, in order, all of its possible values. The
values of the new type will be represented by identifiers, which will be the
constants of the new type.
Examples:
(Plus,Minus,Multi,Divide);
(Mon,Tues,Wed,Thur,Fri,Sat,Sun);
type
Operator
Day
Month
Card
(Jan, Feb, Mar ,Apr, May, Jun, Jul ,Aug, Sep, Oct ,Nov, Dec);
(Club,Diamond,BBart,Spade);
Variables of the above type Card can assume one of four values, namely Club,
Diamond, Heart, or Spade. You are already acquainted with the standard sca-
lar type Boolean which is defined as:
type
Boolean = (False,True);
The relational operators =, (>, >, (, > =, and (= can be applied to all
scalar types, as long as both operands are of the same type (reals and inte-
gers may be mixed). The ordering of the scalar type is used as the basis of the
comparison, i.e. the order in which the values are introduced in the type
definition. For the above type card, the following is true:
Club < Diamond < BBart < Spade
SCALAR AND SUBRANGE TYPES 63
8.1 Scalar Type
The following standard functions can be used with arguments of scalar type:
Suee(Diamond) The successor of Diamond (Heart).
Pred(Diamond) The predecessor of Diamond (Club).
Ord(Diamond) The ordinal value of Diamond (1 [as the ordinal
value of the first value of a scalar type is 0]).
The result type of Succ and Pred is the same as the argument type. The re-
sult type of Ord is Integer.
8.2 Subrange Type
A type may be defined as a subrange of another already defined scalar type.
Such types are called subranges. The definition of a subrange simply speci-
fies the least and the largest value in the subrange. The first constant specifies
the lower bound and must not be greater than the second constant, the upper
bound. A subrange of type Real is not allowed.
Examples:
type
HemiSphere
World
Compas sRange
Upper
Lower
Degree
Wine
(North, South, East, West);
(East, West)
0 .. 360;
'A' .. 'Z';
'a' .. 'z';
(Ce Ie, Fahr, Ream, Ke Iv);
(Red, Whi te, Rose, Sparkling);
The type World is a subrange of the scalar type HemiSphere (called the asso-
ciated scalar type). The associated scalar type of CompasRange is Integer,
and the associated scalar type of Upper and Lower is Char.
You already know the standard subrange type Byte, which is defined as:
type
Byte", 0 .. 255;
A subrange type retains all the properties of its associated scalar type, being
restricted only in its range of values.
64 TURBO Pascal Language Manual
Subrange Type 8.2
The use of defined scalar types and subrange types is strongly recommended
as it greatly improves the readability of programs. Furthermore, run time
checks are included in the program code (see section 8.4) to verify the values
assigned to defined scalar variables and subrange variables. Another advan-
tage of defined types and subrange types is that they often save memory.
TU RBO Pascal allocates only one byte of memory for variables of a defined
scalar type or a subrange type with a total number of elements less than 256.
Similary, integer subrange variables, where lower and upper bounds are both
within the range 0 through 255, occupy only one byte of memory.
8.3 Type Conversion
The Ord function may be used to convert scalar types into values of type inte-
ger. Standard Pascal does not provide a way to reverse this process, i.e. a way
of converting an integer into a scalar value.
In TURBO Pascal, a value of a scalar type may be converted into a value of
another scalar type, with the same ordinal value, by means of the Retype faci-
lity. Retyping is achieved by using the type identifier of the desired type as a
function designator followed by one parameter enclosed in parentheses. The
parameter may be a value of any scalar type except Real. Assuming the type
definitions in sections 8.1 and 8.2, then:
Integer(Heart) 2
Month(l0) Nov
HemiSphere( 2) East
Upper( 14) '0'
Degree( 3) Kelv
Char( 78) 'N'
Integer( '7' ) 55
8.4 Range Checking
The generation of code to perform run-time range checks on scalar and sub-
range variables is controlled with the R compiler directive. The default setting
is {$R -}, i.e. no checking is performed. When an assignment is made to a sca-
lar or a subrange variable while this directive is active ({ $R+}), assignment
values are checked to be within range. It is recommended to use this setting
as long as a program is not fully debugged.
SCALAR AND SUBRANGE TYPES 65
8.4
Example:
66
program Rangecheck;
type
Digit = 0 .. 9;
Var
Dig1,Dig2,Dig3: digit;
begin
Dig1
· -
5;
Dig2
· -
Dig1
+
3;
Dig3
· -
47;
{$R+}
Dig3 . - 55;
{$R- }
Dig3 . - 167;
end.
Range Checking
{valid}
{valid as Dig1 + 3 < = 9}
{invalid but causes no error}
{invalid and causes a run time errod
{invalid but causes no errod
TURBO Pascal Language Manual
STRING TYPE 9
9. STRING TYPE
TURBO Pascal offers the convenience of string types for processing of cha-
racter strings, i.e. sequences of characters. String types are structured types,
and are in many ways similar to array types (see section 10). There is, howe-
ver, one major difference between these: the number of characters in a string
(i.e. the length of the string) may vary dynamically between 0 and a specified
upper limit, whereas the number of elements in an array is fixed.
9.1 String Type Definition
The definition of a string type must specify the maximum number of charac-
ters it can contain, i.e. the maximum length of strings of that type. The defini-
tion consists of the reserved word string followed by the maximum length
enclosed in square brackets. The length is specified by an integer constant in
the range 1 through 255. Notice that strings do not have a default length; the
length must always be specified.
Example:
type
Fi leName strin.g[ 14] ;
Sc reenLine = strin.g[ 80] ;
String variables occupy the defined maximum length in memory plus one byte
which contains the current length of the variable. The individual characters
within a string are indexed from 1 through the length of the string.
9.2 String Expressions
Strings are manipulated by the use of string expressions. String expressions
consist of string constants, string variables, function designators, and opera-
tors.
The plus-sign may be used to concatenate strings. The Concat function (see
section 9.5) performs the same function, but the + operator is often more
convenient. If the length of the result is greater than 255, a run-time error oc-
curs.
STRING TYPE 67
9.2
Example:
'TURBO ' + 'Pascal'
, 123' + '.' + '456'
'A ' + 'B' + ' C ' + 'D
= 'TURBO Pascal'
= '123.456'
='A BCD'
String Expressions
The relational ope--rators =, (>, >, (, > =, and (= are lower in precedence
than the concatenation operator. When applied to string operands, the re--
suit is a Boolean value ( True or False). When comparing two strings, single
cha--racters are compared from the left to the right. If the strings are of
dif--ferent length, but equal up to and including the last character of the
shortest string, then the shortest string is considered the smaller.
Strings are equal only if their lengths as well as their contents are iden--
ti--cal.
Examples:
'A' < 'B'
'A' > 'b'
'2' < '12'
'TURBO' = 'TURBO '
'TURBO ' = 'TURBO '
'Pascal Compiler' < 'Pascal compiler'
is true
is false
is false
is true
is false
is true
9.3 String Assignment
The assignment operator is used to assign the value of a string expression
to a string variable.
Example:
.Age := 'fiftieth';
Line := 'Many happy returns on your' + .Age + ' birthday. ';
If the maximum length of a string variable is exceeded (by assigning too
many characters to the variable), the exceeding characters are truncated.
E.g., if the variable Age above was declared to be of type stringl51. then
after the assignment, the variable will only contain the five leftmost
characters: 'fifti'.
68 TURBO Pascal Language Manual
String Procedures 9.4
9.4 String Procedures
The following standard string procedures are available in TURBO Pascal:
9.4.1 Delete
Syntax: Delete ( St , Pos ,Num )
Delete removes a sU,bstring con--taining Num characters from St starting at
po--sition Pos. St is a string variable and both Pos and Num are integer
expres--sions. If Pos is greater than Length ( St ), no charac--ters are
removed. If an attempt is made to delete characters beyond the end of the
string (j.e. Pos + Num exceeds the length of the string). only charac--ters
within the string are deleted. If Pos is outside the range 1 .. 255, a run
time error occurs.
If St has the value 'ABCDEFG' then:
Delete(St, 2, 4) will give St the value 'AFG'.
Delete(St, 2,10) will give St the value 'A'.
9.4.2 Insert
Syntax: Insert ( Obj, Target, Pos )
Insert inserts the string Obj into the string Target at the position Pos.
Obj is a string expression, Target is a string variable, and Pos is an in--
teger ex--pression. If Pos is greater than Length( Target). then obj is
conca--tenated to Target. If the result is longer than the maximum length of
Target. then excess characters will be truncated and Target will only
contain the left--most characters. If Pos is out--side the range 1 .. 255, a run
time error occurs.
If St has the value 'ABCDEFG' then:
Insert ( 'XX' ,St, 3) will give St the value 'ABXXCDEFG'
STRING TYPE 69
9.4.3 Str
9.4.3 Str
Syntax: Str ( Value, St )
The Str procedure con--verts the numeric value of Value into a string and
stores the result in St. Value is a write parameter of type integer or of
type real, and Str- Var is a string variable. Write parameters are ex--pres--
sions with special formatting commands (see sec--tion 14.6.3 ).
If I has the value 1234 then:
Str(I :5,St) givesSt the value' 1234'.
If X has the value 2.5E4 then:
Str(X:10:0,St) givesSt the value' 2500' .
8-bit systems only: a function using the Str procedure must never be called
by an expression in a Write or Writeln statement.
9.4.4 Val
Syntax: Val ( St , Var , Code)
Val converts the string expression St to an integer or a real value (de--
pending on the type of the variable Va,) and stores this value in Var. St
must be a string expressing a nume--ric value according to the rules applying
to numeric constants (see section 4.2). Neither leading nor trai--ling spaces
are allowed. Var must be an Integer or a Real variable and Code must be an
integer variable. If no errors are detected, the variable Code is set to O.
Otherwise Code is set to the position of the first character in error, and
the value of Var is unde--fined.
If St has the value '234' then:
Val (St, I ,Resul t) gives I the value 234 and Result the value 0
If St has the value '12x' then:
Val (St, I ,Resul t) gives I an undefined value and Result the value 3
If St has the value '2.5E4', and X is a Real variable, then:
Val (St, X,Resul t) gives X the value 2500 and Result the value 0
8-bit systems only: a function using the Var procedure must never be called
by an expression in a Write or Writeln statement.
70 TURBO Pascal Language Manual
String Functions 9.5
9.5 String Functions
The following standard string functions are available in TURBO Pascal:
9.5.1 Copy
Syntax: Copy (St , Pos , Num )
Copy returns a substring con--taining Num characters from St starting at po--
sition Pos. St is a string expression and both Pos and Num are integer
expressions. If Pos exceeds the length of the string, the empty string is
returned. If an attempt is made to get characters beyond the end of the
string (i.e. Pos + Num exceeds the length of the string)' only the charac--
ters within the string are returned. If Pos is outside the range 1 .. 255, a
run time error occurs.
If St has the value 'ABCDEFG' then:
Copy(St, 3, 2) returns the value 'CD'
Copy(St, 4,10) returns the value 'DEFG'
Copy(St, 4, 2) returns the value 'DE'
9.5.2 Concat
Syntax: Concat (St1 , St2 { , StN } )
The Concat function returns is a string which is the concatenation of its
arguments in the order in which they are specified. The arguments may be
any number of string expressions se--pa--rated by commas ( sa, St2 .. StN).
If the length of the result is greater than 255, a run-time error occurs.
As explained in sec--tion 9.3, the + operator can be used to obtain the same
result, often more conveniently. Concat is in--cluded only to maintain compa--
tibility with other Pascal compilers.
If St1 has the value' TURBO' and St2 the value 'is fastest' then:
Concat(Stl,' PASCAL',St2)
returns the value 'TURBO PASCAL is fastest'
STRING TYPE 71
9.5.3 Length
9.5.3 Length
Syntax: Length ( St )
Returns the length of the string expression St, i.e. the number of cha--rac--
ters in St. The type of the result is integer.
If St has the value '123456789' then:
Length(St) returns the value 9
9.5.4 Pos
Syntax: Pos ( Obj , Target)
The Pas function scans the string Target to find the first occurrence of
Obj within Target. Obj and Target are string expressions, and the type of
the result is inte--ger. The result is an integer denoting the position
within Target of the first character of the matched pat--tern. The position
of the first character in a string is 1. If the pattern is not found, Pas
returns O.
If St has the value 'ABCDEFG' then
pose 'DE' ,St) returns the value 4
pose 'H' ,St) returns the value 0
72 TURBO Pascal Language Manual
Strings and Characters 9.6
9.6 Strings and Characters
String types and the standard scalar type Char are compatible. Thus, when-
ever a string value is expected, a char value may be specified instead and vice
versa. Furthermore, strings and characters may be mixed in expressions.
When a character is assigned a string value, the length of the string must be
exactly one; otherwise a run-time error occurs.
The characters of a string variable may be accessed individually through
string indexing. This is achieved by appending an index expression of type
integer, enclosed in square brackets, to the string variable.
Examples:
Buffer[ 5]
Line[Length(Line)-l]
Ord(Line[0] )
As the first character of the string (at index 0) contains the length of the
string, Length(String) is the same as Ord(String[0]). If assignment is
made to the length indicator, it is the responsibility of the programmer to
check that it is less than the maximum length of the string variable. When the
range check compiler directive R is active ({ $R+}), code is generated which
insures that the value of a string index expression does not exceed the
maximum length of the string variable. It is, however, still possible to index a
string beyond its current dynamic length. The characters thus read are
random, and assignments beyond the current length will not affect the actual
value of the string variable.
STRING TYPE 73
9.6 Strings and Characters
Notes:
74 TURBO Pascal Language Manual
ARRAY TYPE 10
10. ARRAVTYPE
An array is a structured type consisting of a fixed number of components
which are all of the same type, called the component type or the base type.
Each component can be explicitly accessed by indices into the array. Indices
are integer expressions within square brackets suffixed to the array identifier,
and their type is called the index type.
10.1 Array Definition
The definition of an array consists of the the reserved word array followed by
the index type, enclosed in square brackets, followed by the reserved word of,
followed by the component type.
Examples:
type
Day = (Mon,Tue,Wed,Thu,Fri,Sat,Sun)
Var
WorkHour
Week
.. 8] of Integer;
.. 7] of Day;
type
Players
Hand
LegalBid
Bid
(Player1,Player2,Player3,Player4);
(One,Two,Pair,TwoPair,Three,Straight,
Flush, FullHouse, Four, StraightFlush,RSF);
1. .200;
Var
Player
Pot
of LegalBid;
of Hand;
Bid;
An array component is accessed by suffixing an index enclosed in square
brackets to the array variable identifier:
Player[Player3] : = FullHouse;
Pot [Player3] := 100;
Player[Player4] : = Flush;
Pot [Player4] := 50;
ARRAY TYPE 75
10.1 Array Definition
As assignment is allowed between any two variables of identical type, entire
arrays can be copied with a single assignment statement.
The R compiler directive controls the generation of code which will perform
range checks on array index expressions at run-time. The default mode is pas-
sive, i.e. {$R-l. and the { $R+} setting causes all index expressions to be
checked against the limits of their index type.
10.2 Multidimensional Arrays
The component type of an array may be any data type, i.e. the component
type may be another array. Such a structure is called a multidimensional ar-
ray.
Example:
type
Card
Suit
AIlCards
Var
(Two,Three,Four,Five, Six, Seven, Eight ,Nine,
Ten,Knight,Queen,King,Ace);
(Hearts,Spade,Clubs,Diamonds);
array[Suit] of array[1 .. 13] of Card;
Deck: AIlCards;
A multidimensional array may be defined more conveniently by specifying the
multiple indices thus:
type
AIICards = array[Suit,1 .. 13] of Card;
A similar abbreviation may be used when selecting an array component:
Deck[Hearts,10] is equivalent to Deck[Hearts] [10]
It is, of course, possible to define multidimensional arrays in terms of pre-
viously defined array types.
76 TURBO Pascal Language Manual
Multidimensional Arrays
Example:
type
Pupils
Class
Scool
Var
J,P,Vacant
ClassA,
ClassB
string[ 10] ;
a r r ~ [ l .. 30] of Pupils;
a r r ~ [ l .. 100] of Class;
Integer
Class;
NewTownScool: Scool;
After these definitions, all of the following assignments are legal:
ClassA[J] :='Peter';
NewTownScool[5] [211: '=Peter Brown';
10.2
NewTownScoo I [8, J] : =NewTownScoo I [7, J]; {pupil no. J changed class}
C lassA[Vacant] : =ClassB[ p] ; {pupil no. P changes Class and numbed
10.3 Character Arrays
Character arrays are arrays with one index and components of the standard
scalar type Char. Character arrays may be thought of as strings with a con-
stant length.
In TURBO Pascal, character arrays may participate in string expressions, in
which case the array is converted into a string of the length of the array. Thus,
arrays may be compared and manipulated in the same way as strings, and
string constants may be assigned to character arrays, as long as they are of
the same length. String variables and values computed from string expres-
sions cannot be assigned to character arrays.
10.4 Predefined Arrays
TURBO Pascal offers two predefined arrays of type Byte, called Mem and
Port, which are used to access CPU memory and data ports. These are
discussed in appendices A and B .
ARRAY TYPE 77
10.4 Predefined Arrays
Notes:
78 TURBO Pascal Language Manual
RECORD TYPE 11
11. RECORD TYPE
A record is a structure consisting of a fixed number of components, called
fields. Fields may be of different type and each field is given a name, the field
identifier, which is used to select it.
11.1 Record Definition
The definition of a record type consists of the reserved word record suc-
ceeded by a field list and terminated by the reserved word end. The field list is
a sequence of record sections separated by semi-colons, each consisting of
one or more identifiers separated by commas and terminated by a colon and a
type identifier. Each record section thus specifies the type and identifier for
one or more fields.
Example:
type
Date record
Var
Day: 1. .31;
Month: (Jan,Feb,Mar,Apr,MaY,Jun,
July ,Aug, Sep, Oc t ,Nov, Dec);
Year: 1900 .. 1999;
end;
Bi rth: Date;
WorkDay: array[ 1. .5] of date;
Day, Month, and Yearare field identifiers. A fieid identifier must be unique
only within the record in which it is defined. A field is referenced by the va-
riable identifier and the field identifier separated by a period.
Examples:
Birth.Month .- Jun;
Birth.Year := 1950;
WorkDay[Current] := workDay[Current-1];
Note that, similar to array types, assignment is allowed between entire re-
cords of identical types. As record components may be of any type, con-
structs like the following record of records of records are possible:
RECORD TYPE 79
11.1 Record Definition
type
Name record
Fami lyName: string[ 32];
ChristianNames: a r r ~ [ 1 .. 3] of string[16];
end;
Rate record
NormalRate, OverI'ime,
NightTime, Weekend: Integer
end;
Date record
Day: 1. .31;
Month: (Jan,Feb,Mar,Apr,May,Jun,
JulY,Aug,Sep,Oct,Nov,Dec);
Year: 1900 .. 1999;
end;
Person = record
Wages
ID: Name;
Time: Date;
end;
record
Individual: Person;
Cost: Rate;
end
Var Salary, Fee: Wages;
Assuming these definitions, the following assignments are legal:
80
Salary : = Fee;
Salary.Cost.Overtime .- 950;
Salary. Individual. Time : = Fee. Individual. Time;
Salary.Individual.ID.FamilyName := 'Smith'
TURBO Pascal Language Manual
With Statement 11.2
11 .2 With Statement
The use of records as describes above does sometimes result in rather lengthy
statements; it would often be easier if we could access individual fields in a
record as if they were simple variables. This is the function of the with state-
ment: it 'opens up' a record so that field identifiers may be used as variable
identifiers.
A with statement consists of the reserved word with followed by a list of re-
cord variables separated by commas followed by the reserved word do and fi-
nallya statement.
Within a with statement, a field is designated only by its field identifier, i.e.
without the record variable identifier:
wi th Salary do
begin
Individual : = NewEmployee;
Cost := StandardRates;
end;
Records may be nested within with statements, i.e. records of records may
be 'opened' as shown here:
with Salary, Individual, ID do
begin
Fami lyName : = 'Smi th';
ChristianNames[l] := 'James';
end
This is equivalent to:
with Salary do with Individual do with ID do
The maximum 'depth' of this nesting of with sentences, i.e. the maximum
number of records which may be 'opened' within one block, depends on your
implementation and is discussed in appendices A and B .
RECORD TYPE 81
11.3 Variant Records
11.3 Variant Records
The syntax of a record type also provides for a variant part, i.e. alternative re-
cord structures which allows fields of a record to consist of a different number
and different types of components, usually depending on the value of a tag
field.
A variant part consists of a tag-field of a previously defined type, whose
values determine the variant, followed by labels corresponding to each
possible value of the tag field. Each label heads a field list which defines the
type of the variant corresponding to the label.
Assuming the existence of the type:
Origin = (Citizen, Alien);
and of the types Name and Date, the following record allows the field Citi-
zenShip to have different structures depending on whether the value of the
field is Citizen or Alien:
type
Person = record
PersonName: Name;
Bi rtbDate: Date;
case CitizenShip: Origin of
Citizen: (BirthPlace: Name);
end
Al ien: (CountryOfOrigin: Name;
DateOfEntry: Date;
Permi ttedUnt i I: Date;
PortOfEntry: Name)
In this variant record definition, the tag-field is an explicit field which may be
selected and updated like any other field. Thus, if Passenger is a variable of
type Person, statements like the following are perfectly legal:
Passenger.CitizenShip := Citizen;
wlthPassenger, PersonName do
if CitizenShip = Alien then writeln(FamiIYName);
82 TURBO Pascal Language Manual
Variant Records 11.3
The fixed part of a record, i.e. the part containing the common fields, must al-
ways precede the variant part. I n the above example, the fields PersonName
and BirthDate are the fixed fields. A record can only have one variant part. In a
variant, the parentheses must be present, even if they will enclose nothing.
The maintenance of tag field values is the responsibility of the programmer
and not of TURBO Pascal. Thus, in the Person type above, the field DateOf-
Entry can be accessed even if the value of the tag field CitizenShip is not
Alien. Actually, the tag field identifier may be omitted alltogether, leaving only
the type identifier. Such record variants are known as free unions, as opposed
to record variants with tag fields which are called discriminated unions. The
use of free unions is infrequent and should only be practiced by experienced
programmers.
RECORD TYPE 83
11.3 Variant Records
Notes:
84 TURBO Pascal Language Manual
SET TYPE 12
12. SETTVPE
A set is a collection of related objects which may be thought of as a whole.
Each object in such a set is called a member or an element of the set. Examp-
les of sets could be:
1) All integers between a and 100
2) The letters of the alphabet
3) The consonants of the alphabet
Two sets are equal if and only if their elements are the same. There is no or-
dering involved, so the sets [1,3,51, [5,3,1] and [3,5,1] are all equal. If the
members of one set are also members of another set, then the first set is said
to be included in the second. In the examples above, 3) is included in 2).
There are three operations involving sets, similar to the operations addition,
multiplication and subtraction operations on numbers:
The union (or sum) of two sets A and B (written A+B) is the set whose
members are members of either A or B. For instance, the union of [1 ,3,5,7]
and [2,3,4] is [1,2,3,4,5,7].
The intersection (or product) of two sets A and B (written A*B) is the set
whose members are the members of both A and B. Thus, the intersection
of [1,3,4,5,7] and [2,3,4] is [3,4].
The relative complement of B with respect to A (written A-B) is the set
whose members are members of A but not of B. For instance, [1,3,5,7]-
[2,3,4] is [1,5,7].
12.1 Set Type Definition
Although in mathematics there are no restrictions on the objects which may
be members of a set, Pascal only offers a restricted form of sets. The mem-
bers of a set must all be of the same type, called the base type, and the base
type must be a simple type, i.e. any scalar type except real. A set type is intro-
duced by the reserved words set of followed by a simple type.
RECORD TYPE 85
12.1
Examples:
type
DaysOfMonth = set of 0 .. 31;
WorkWeek = set of Mon .. Fri;
Letter = set of 'A' .. 'Z';
AdditiveColors = set of (Red,Green,Blue);
Characters = set of Char;
Set Type Definition
In TURBO Pascal, the maximum number of elements in a set is 256, and the
ordinal values of the base type must be within the range 0 through 255.
12.2 Set Expressions
Set values may be computed from other set values through set expressions.
Set expressions consist of set constants, set variables, set constructors, and
set operators.
12.2.1 S ~ t Constructors
A set constructor consists of one or more element specifications, separated
by commas, and enclosed in square brackets. An element specification is an
expression of the same type as the base type of the set, or a range expressed
as two such expressions separated by two consecutive periods ( .. ).
Examples:
['T', 'U', 'R', 'B', '0']
[X,Y]
[X .. y]
[1. .5]
[ 'A' .. 'Z' , 'a' .. 'z' , '0' .. '9' ]
[1,3 .. 10,12]
[ ]
The last example shows the empty set, which, as it contains no expressions to
indicate its base type, is compatible with all set types. The set [1 .. 5) is equiva-
lent to the set [1,2,3,4,5]. IfX>Y then [X .. Y) denotes the empty set.
86 TURBO Pascal Language Manual
Set Operators 12.2.2
12.2.2 Set Operators
The rules of composition specify set operator precedences according to the
following three classes of operators:
1) * Set intersection.
2) + Set union.
Set difference.
3) Test on equality.
<> Test on inequality.
>= True if the second operand is included in the first operand.
<= True if the first operand is included in the second operand.
IN Test on set membership. The second operand is of a set type, and
the first operand is an expression of the same type as the base
type of the set. The result is true if the first operand is a member
of the second operand, otherwise it is false.
There is no operator for strict unclusion, but it may be programmed as
A*B=[].
Set expressions are often useful to clarify complicated tests. For instance, the
test:
if (Ch= 'T') or (Cll: 'U') or (Ch= 'R') or (Ch= 'B') or (Ch= '0' )
can be expressed much clearer as:
Ch in ['T', 'U', 'R', 'B', '0']
And the test:
if (Ch >= ' 8') and (Ch < = ' 9') then
is better expressed as:
if Ch in.[ '8' .. ' 9'] then
RECORD TYPE 87
12.3 Set Assignments
12.3 Set Assignments
Values resulting from set expressions are assigned to set variables using the
assignment operator . - .
Examples:
88
type
ABCII = set of 0 .. 127;
Var
NoPrint, Print ,AIlChars: ASCII;
begin
AIIChars : = [0 .. 127];
NoPrint : = [0 .. 31,127];
Print : = AllChars - NoPrint;
end.
TURBO Pascal Language Manual
TYPED CONSTANTS 13
13. TYPED CONSTANTS
Typed constants are a TURBO speciality. A typed constant may be used
exactly like a variable of the same type. Typed constants may thus be used as
'initialized variables', because the value of a typed constant is defined, whe-
reas the value of a variable is undefined until an assignment is made. Care
should be taken, of course, not to assign values to typed constants whose va-
lues are actually meant to be constant.
The use of a typed constant saves code if the constant is used often in a pro-
gram, because a typed constant is included in the program code only once,
whereas an untyped constant is included every time it is used.
Typed constants are defined like untyped constants (see section 5.2.2). ex-
cept that the definition speficies not only the value of the constant but also
the type. In the definition the typed constant identifier is succeeded by a colon
and a type identifier, which is then followed by an equal sign and the actual
constant.
13.1 Unstructured Typed Constants
An unstructured typed constant is a constant defined as one of the scalar ty-
pes:
const
NumberOfCars: Integer = 1267;
Interest: Real = 12.67;
Heading: string[7] = 'SECTION';
Xon: Char = ~ Q ;
Contrary to untyped constants, a .typed constan't may be used in place of a
variable as a variable parameter to a procedure or a function. As a typed
constant is actually a variable with a constant value, it cannot be used in the
definition of other constants or types. Thus, as Min and Max are typed
constants, the following construct is illegal:
const
Min: Integer 0;
Max: Integer 50;
type
Range: array[Min .. Max] of integer
TYPED CONSTANTS 89
13.2 Structured Typed Constants
13.2 Structured Typed Constants
Structured constants comprise array constants, record constants, and set
constants. They are often used to provide initialized tables and sets for tests,
conversions, mapping functions, etc. The following sections describe each
type in detail.
13.2.1 Array Constants
The definition of an array constant consists of the constant identifier succee-
ded by a colon and the type identifier of a previously defined array type follo-
wed by an equal sign and the constant value expressed as a set of constants
separated by commas and enclosed in parentheses.
Examples:
type
Status
StringRep
const
(Act ive, Pass i ve, Wai t ing);
of string[7];
Stat: StringRep = ('active', 'paSSive', 'waiting');
The example defines the array constants Stat, which may be used to convert
values of the scalar type Status into their corresponding string represen-
tations. The components of Stat are:
Stat [Act ive]
Stat[Passive]
Stat [Wai t ing]
'active'
'passive'
'waiting'
The component type of an array constant may be any type except File types
and Pointer types. Character array constants may be specified both as single
characters and as strings. Thus, the definition:
const
Digits: .. 9] of Char =
('0', '1', '2', '3', '4', '5', '6', '7', '8', '9');
may be expressed more conveniently as:
const
Digits: .. 9] of Char '0123456789';
90 TURBO Pascal Language Manual
Multidimensional Array Constants 13.2.2
13.2.2 Multidimensional Array Constants
Multidimensional array constants are defined by enclosing the constants of
each dimension in separate sets of parentheses, separated by commas. The
innermost constants correspond to the rightmost dimensions.
Example:
type
Cube = a r r ~ [ 0 .. 1,O .. 1,O .. 1] of integer;
const
Maze: Cube = (((O,1),(2,3»,((4,5),(6,7));
begin
Writeln(Maze[0,0,0], , 0');
Writeln(Maze[0,0,11, , 1');
Writeln(Maze[0, 1,0], , 2');
Writeln(Maze[0, 1, 11, , 3');
Writeln(Maze[I,0,0],' 4');
Writeln(Maze[l,0,11,' 5');
Writeln(Maze[I,I,0],' 6');
Writeln(Maze[ 1, 1, 11, , 7');
end.
13.2.3 Record Constants
The definition of a record constant consists of the constant identifier succe-
ded by a colon and the type identifier of a previously defined record type follo-
wed by an equal sign and the constant value expressed as a list of field con-
stants separated by semi-colons and enclosed in parentheses.
Examples:
type
Point
as
UI
Computer
TYPED CONSTANTS
record
X,Y, Z: integer;
end;
(CPM80,CPM86,MSDOS,Unix);
(CCP,SomethingElse,MenuMaster);
record
OperatingSystems: a r ~ [ I .. 4] of OS;
Userlnterface: UI;
end;
91
13.2.3 Record Constants
canst
Origo: Point = (X:0; Y:0; Z:0);
SuperComp: Computer =
(OperatingSystems: (CPM80,CPM86,MSDOS,Unix);
Userlnterface: MenuMaster);
Plane1: .. 3] of Point =
((X: 1;Y:4; Z:5), (X: 10;Y: -78; Z:45), (X: 100;Y: 10; Z: -7»;
The field constants must be specified in the same order as they appear in the
definition of the record type. If a record contains fields of file types or pointer
types, then constants of that record type cannot be specified. If a record con-
stant contains a variant, then it is the responsibility of the programmer to spe-
cify only the fields of the valid variant. If the variant contains a tag field, then
its value must be specified.
13.2.4 Set Constants
A set constant consists of one or more element specifications separated by
commas, and enclosed in square brackets. An element specification must be
a constant or a range expression consisting of two constants separated by
two consecutive periods ( .. ).
Example:
type
Up set of 'A' .. 'Z';
Low set of 'a' .. 'z';
const
UpperCase: Up ['A' .. 'Z'];
Vocals Low ['a', 'e', 'i', '0', 'u', 'Y'];
Delimiter: set of Char =
[, , .. ,/",:, .. ,?",[, .. .. ,-,];
92 TURBO Pascal Language Manual
FILE TYPES 14
14. FILE TYPES
Computer programs frequently produce large amounts of data which is not
required until later in the program or even by some other program. As this
data often exceeds the available memory, data can be written to and read
from named units placed on magnetic devices such as diskettes or hard disks.
These units are called files.
A file consists of a sequence of components of equal type. The number of
components in a file (the size of the file) is not determined by the definition of
the file; instead the Pascal system keeps track of file accesses through a file
pointer, and each time a component is written to or read from a file, the file
pointer of that file is advanced to the next component. As all components of a
file are of equal length, the position of a specific component can be calcula-
ted. Thus, the file pointer can be moved to any component in the file, provid-
ing random access to any element of the file.
14.1 File Type Definition
A file type is defined by the reserved words file of followed by the type of the
components of the file, and a file identifier is declared by the same words fol-
lowed by the identifier of a previously defined file type.
Examples:
type
ProductName = string[80];
Product = file of recoDd
Var
Name: ProductName;
IterrNumber: Real;
InStock: Real;
MinStock: Real;
Suppl ier: Integer;
end;
ProductFile: Product;
ProductNames: file of ProductName;
The component type of a file may be any type, except a file type. (Le., with re-
ference to the example above, file of Product is not allowed). File variables
may appear neither in assignments nor in expressions.
FILE TYPES 93
14.2 Operations on Files
14.2 Operations on Files
The following sections describe the procedures available for file handling. The
identifier Filvar used throughout denotes a file variable identifier declared as
described above.
14.2.1 Assign
Syntax: Assign( FilVar, Str)
Str is a string expression yielding any legal file name. This file name is assig-
ned to the file variable FilVar, and all further operation on FiIVar will operate
on the disk file Str. Assign should never be used on a file which is in use.
14.2.2 Rewrite
Syntax: Rewrite( FilVar)
A new disk file of the name assigned to the file variable FilVar is created and
prepared for processing. and the file pointer is set to the beginning of the file.
i.e. component no. O. Any previously existing file with the same name is era-
sed. A disk file created by rewrite is initially empty, i.e. it contains no ele-
ments.
14.2.3 Reset
Syntax: Reset( FiIVar)
The disk file of the name assigned to the file variable FilVar is prepared for
processing, and the file pointer is set to the beginning of the file, i.e. compo-
nent no. O. FilVar must name an existing file, otherwise an I/O error occurs.
94 TURBO Pascal Language Manual
Read 14.2.4
14.2.4 Read
Syntax: Read( FilVar, Var)
Var denotes one or more variables of the component type of FilVar, sepa-
rated by commas. Each variable is read from the disk file, and following each
read operation, the file pointer is advanced to the next component.
14.2.5 Write
Syntax: Write( FilVar, Var)
Var denotes one or more variables of the component type of FilVar, sepa-
rated by commas. Each variable is written to the disk file, and following each
write operation, the file pointer is advanced to the next component.
14.2.6 Seek
Syntax: Seek( FilVar, n)
Seek moves the file pointer is moved to the n'th component of the file deno-
ted by FilVar. n is an integer expression. The position of the first component is
O. Note that in order to expand a file it is possible to seek one component
beyond the last component. The statement
Seek(Fi IVar, Fi leSize(Fi IVar»;
thus places the file pointer at the end of the file ( FileSize returns the number
of components in the file, and as the components are numbered from zero,
the returned number is one greater than the number of the last component).
14.2.7 Flush
Syntax: Flush( FilVar)
Flush empties the internal sector buffer of the disk file FiIVar, and thus assu-
res that the sector buffer is written to the disk if any write operations have ta-
ken place since the last disk update. Flush also insures that the next read ope-
ration will actually perform a physical read from the disk file. Flush should ne-
ver be used on a closed file.
FILE TYPES 95
14.2.8 Close
14.2.8 Close
Syntax: Close( FilVar)
The disk file associated with FilVar is closed, and the disk directory is updated
to reflect the new status of the file. Notice that in multi-user environments it
is often necessary to Close a file, even if it has only been read from.
14.2.9 Erase
Syntax: Erase( FilVar)
The disk file associated with FilVar is erased. If the file is open, i.e. if the file
has been reset or rewritten but not closed, it is good programming practice to
close the file before erasing it.
14.2.10 Rename
Syntax: Rename( FilVar, Str)
The disk file associated with FilVar is renamed to a new name given by the
string expression Str. The disk directory is updated to show the new name of
the file, and further operations on FilVar will operate on the file with the new
name. Rename should never be used on an open file.
Notice that it is the programmer's responsibility to assure that the file named
by Str does not already exist. If it does, multiple occurrences of the same
name may result. The following function returns True if the file name passed
as a parameter exists, otherwise it returns False:
96
function Exist(FileName: Name): boolean;
Var
Fi 1: file;
begin
Assign(Fil, FileName);
{$1 - }
Reset(Fil);
{$1+ }
Exist := OOresult 0)
end;
TURBO Pascal Language Manual
File Standard Functions 14.3
14.3 File Standard Functions
The following standard functions are applicable to files:
14.3.1 EOF
Syntax: EOF( FilVar)
A Boolean function which returns True if the file pointer is positioned at the
end of the disk file, i.e. beyond the last component of the file. If not, EOF re-
turns False.
14.3.2 RlePos
Syntax: FilePos( FilVar)
An integer function which returns the current position of the file pointer. The
first component of a file is O.
14.3.3 RleSize
Syntax: FileSize( FilVar)
An integer function which returns the size of the disk file expressed as the
number of components in the file. If FileSize(FiIVar) is zero, the file is empty.
14.4 Using Files
Before using a file, the Assign procedure must be called to assign the file
name to a file variable. Before input and/or output operations are performed.
the file must be opened with a call to Rewrite or Reset. This call will set the
file pointer to point to the first component of the disk file. i.e. FilePos(FiIVar)
= O. After Rewrite, FileSize(FiIVar) is O.
FILE TYPES 97
14.4 Using Files
A disk file can be expanded only by adding components to the end of the
existing file. The file pointer can be moved to the end of the file by executing
the following sentence:
Seek(FilVar, FileSize(FilVar»;
When a program has finished its input/output operations on a file, it should
always call the Close procedure. Failure to do so may result in loss of data, as
the disk directory is not properly updated.
The program below creates a disk file called PRODUCTS.DTA, and writes 100
records of the type Product to the file. This initializes the file for subsequent
random access (i.e. records may be read and written anywhere in the file).
98
program Ini tProductFi Ie;
const
MaXNumberOfProducts = 100;
type
ProductName = string[20];
Product = record
Name: ProductName;
IteIIiNumber: Integer;
InStock: Real;
Supplier: Integer;
end;
Var
ProductFile: file of Product;
ProductRec: Product;
I: Integer;
begin
As s ign(ProductFile, 'PRDIXJCI'. UTA' );
Rewrite(ProductFile); {open the file and delete any data}
with ProductRec do
begin
Name : = "; InStock . - 0; Supplier : = 0;
for I := 1 to MaXNumberOfProducts do
begin
IteIIiNumber := I;
Wri te(ProductFi Ie, ProductRec);
end;
end;
01 ose(ProductFi Ie);
end.
TURBO Pascal Language Manual
Using Files 14.4
The following program demonstrates the use of Sseek on random files. The
program is used to update the Pro duct File created by the program in the pre-
vious example.
program UpDateProductFi Ie;
const
MaxNumberOfProducts = 100;
type
ProductName = string[20];
Product = recoDd
Var
Name: ProductName;
ItemNumber: Integer;
InStock: Real;
Suppl ier: Integer;
end;
ProductFile: file of Product;
ProductRec: Product;
I, Pnr: Integer;
begin
Assign(ProductFile, 'PRODOCT.DTA'); Reset(ProductFile);
01 rSc r;
Write( 'Enter product number (0= stop) ,); Readln(Pnr);
while Pnr in [1 .. MaXNumberOfProducts] do
begin
Seek(ProductFile,Pnr-l); Read(ProductFile,ProductRec);
with ProductRec do
begin
Write( 'Enter name of product (',Name:20,') ,);
Readln(Name) ;
Write('Enter number in stock (',InStock:20:0,') ');
ReadlnCInStock) ;
Write( 'Enter supplier number (',Supplier:20,') ,);
Readln(Suppl ier);
It emNumber: =Pnr;
end;
Seek(ProductFile,Pnr-l);
Write(ProductFile,ProductRec);
C 1 rScr; Wri te In;
Write( 'Enter product number (0= stop) ,); Readln(Pnr);
end;
Close(ProductFile);
end..
FILE TYPES 99
14.5 Text Files
14.5 Text Files
Unlike all other file types, text files are not simply sequences of values of
some type. Although the basic components of a text file are characters, they
are structured into lines, each line being terminated by an end-of-line marker
(a CR/LF sequence). The file is further ended by an end-of-file marker (a Ctrl-
Z). As the length of lines may vary, the position of a given line in a file cannot
be calculated. Text files can therefore only be processed sequentially. Further-
more, input and output cannot be performed simultaneously to a text file.
14.5.1 Operations on Text Rles
A text file variable is declared by referring to the standard type identifier Text.
Subsequent file operations must be preceded by a call to Assign and a call to
Reset or Rewrite must furthermore precede input or output operations.
Rewrite is used to create a new text file, and the only operation then allowed
on the file is the appending of new components to the end of the file. Reset is
used to open an existing file for reading, and the only operation allowed on
the file is sequential reading. When a new textfile is closed, an end-of-file
mark is automatically appended to the file.
Character input and output on text files is made with the standard proce-
dures Read and Write. Lines are processed with the special text file operators
Rea dIn , Writeln, and Eoln :
Readln( Filvar)
Writeln( Filvar)
Eoln( Filvar)
100
Skips to the beginning of the next line, i.e. skips all charac-
ters up to and including the next CR/LF sequence.
Writes a line marker, i.e. a CR/LF sequence, to the text-
file.
A Boolean function which returns True if the end of the
current line has been reached, i.e. if the file pointer is posi-
tioned at the CR character of the CR/LF line marker. If
EOF( Filvar) is true, Eoln( Filvar) is also true.
TURBO Pascal Language Manual
Operations on Text Files 14.5.1
When applied to a text file, the EOF function returns the value True if the file
pointer is positioned at the end-of-file mark (the CTRl/Z character ending the
file). The Seek and Flush procedures and the FilePos and FileSize functions
are not applicable to text files.
The following sample program reads a text file from disk and prints it on the
pre-defined device Lst which is the printer. Words surrounded by Ctrl-S in the
file are printed underlined:
program TextFi leDemo;
Var
Fi IVar: Text;
Line,
ExtraLine: string[ 255] ;
I: Integer;
UnderLine: Boolean;
string[ 14] ; Fi leName:
begin
UnderLine . - False;
Write('Enter name of file to list: ,);
Read In( F i I eName) ;
Ass ign(Fi IVar, Fi leName);
Reset(Fi IVar);
while not Eof(FiIVar) do
begin
Readln(Fi IVar, Line);
I := 1; ExtraLine := ";
for I := 1 to Length(Line) do
begin
if Line[ I then
begin
Write(Lst,Line[I]);
if UnderLine then Ext raLine . - Ext
else ExtraLine := ExtraLine+' ';
end
else UnderLine : = not UnderLine;
end;
Writeln(Lst,ExtraLine);
end; {while not Eof}
end.
Further extensions of the procedures Read and Write, which facilitate conve-
nient handling of formatted input and output, are described in section 14.6 .
FILE TYPES 101
14.5.2 Logical Devices
14.5.2 Logical Devices
In TURBO Pascal, external devices such as terminals, printers, and modems
are regarded as logical devices which are treated like text files. The following
logical devices are available:
CON:
TRM:
KBD:
L5T:
AUX:
U5R:
The console device. Output is sent to the operating system's con-
sole output device, usually the CRT, and input is obtained from the
console input device, usually the keyboard. Contrary to the TRM:
device (see below), the CON: device provides buffered input. In
short, this means that each Read or Readln from a textfile assigned
to the CON: device will input an entire line into a line buffer, and
that the operator is provided with a set of editing facilities during
line input. For more details on console input. please refer to sections
14.5.3 and 14.6.1 .
The terminal device. Output is sent to the operating system's con-
sole output device, usually the CRT, and input is obtained from the
console input device, usually the keyboard. Input characters are ec-
hoed, unless they are control characters. The only control character
echoed is a carriage return (CR), which is echoed as CR/LF.
The keyboard device (input only). Input is obtained from the operat-
ing system's console input device, usually the keyboard. Input is not
echoed.
The list device (output only). Output is sent to the operating sy-
stem's list device, typically the line priner.
The auxiliary device. Output is sent to the operating system's punch
device, and input is obtained from the operating system's reader de-
vice. Usually, the punch and reader devices refer to a modem.
The user device. Output is sent to the user output routine, and input
is obtained from the user input routine. For further details on user
input and output, please refer to sections A.13 and B.3.3 .
These logical devices may be accessed through the pre-assigned files dis-
cussed in section 14.5.3 or they may be assigned to file variables, exactly like
a disk file. There is no difference between Rewrite and Reset on a file assig-
ned to a logical device, Close performs no function, and an attempt to Erase
such a file will cause an I/O error.
102 TURBO Pascal Language Manual
Logical Devices 14.5.2
The standard functions Eof and Eoln operate differently on logical devices
than on disk files. On a disk file, Eof returns True when the next character in
the file is a Ctrl-Z, or when physical EOF is encountered, and Eoln returns True
when the next character is a CR or a Ctrl-Z. Thus, Eof and Eoln are in fact
"Iook ahead" routines.
As you cannot look ahead on a logical device, Eoln and Eof operate on the last
character read instead of on the next character. In effect, Eof returns True
when the last character read was a Ctrl-Z, and Eoln returns True when the last
character read was a CR or a Ctrl-Z. The following table provides an overview
of the operation of Eoln and Eof:
On Fi les On Logical Devices
Eoln is true if next character if current character
is CR or Ctrl-Z is CR or Ctrl-Z
or if EDF is true
Eof is true if next character if current character
character is Ctrl-Z is Ctrl-Z
or if phys ical EDF
is met
Table 14-1: Operation of EOLN and Eof
Similarly, the Readln procedure works differently on logical devices than on
disk files. On a disk file, Readln reads all characters up to and including the
CR/LF sequence, whereas on a logical device it only reads up to and including
the first CR. The reason for this is again the inability to 'look ahead' on logical
devices, which means that the system has no way of knowing what character
will follow the CR.
14.5.3 Standard Rles
As an alternative to assigning text files to logical devices as described above,
TURBO Pascal offers a number of pre-declared text files which have already
been assigned to specific logical devices and prepared for processing. Thus,
the programmer is saved the reset/rewrite and close processes, and the use
of these standard files further saves code:
FILE TYPES 103
- I
14.5.3 Standard Files
Input The primary input file. This file is assigned to either the CON: device
or to the TRM: device (see below for further details).
Output The primary output file. This file is assigned to either the CON: de-
vice or to the TRM: device (see below for further details)'
Can Assigned to the console device (CON :).
Trm Assigned to the terminal device (TRM :).
Kbd Assigned to the keyboard device (KBD:).
Lst Assigned to the list device (LST:).
Aux Assigned to the auxiliary device (AU X :).
Usr Assigned to the user device (USR:).
Notice that the use of Assign, Reset, Rewrite, and Close on these files is not
only unnecessary, but also illegal.
The logical device referred to by the standard files Input and Output is deter-
mined by the B compiler directive. The default value {$B+} causes the con-
sole device (CON:) to be used, which provides buffered input with editing fa-
cilities (see section 14.6.1 ), but it does not conform to the standard in all
aspects. I n the {$B -} mode, input and output will instead refer to the terminal
device (TRM:) which offers no editing facilities during input, but entries may
follow the formats defined by Standard, Pascal. No differences exist between
the console device and the terminal device on output operations.
Notice that the B compiler directive must be placed at the start of the pro-
gram block, and is thus a global directive which cannot be changed throug-
hout the program text. If some input/output operations are to use the CON:
device, and others the TRM: device, then set the B directive for the most fre-
quently used device and specify the other device explicitly in the remaining
calls to i/o procedures.
Example:
{$B- }
program ReadAndWri tee input, output);
Readln(Varl);
Readln(Con, Var2);
Reads from the TRM: device
Reads from the CON: device
In situations where input is not to be automatically echoed to the screen, in-
put should be made from the standard file Kbd:
Read(Kbd, Var)
104 TURBO Pascal Language Manual
Standard Files 14.5.3
As the standard files Input and Output are used very frequently, they are cho-
sen by default when no file identifier is explicitly stated. The following list
shows the abbreviated text file operations and their equivalents:
Write (Ch)
Read(Ch)
Writeln
Rea dIn
Eat
Eo In
Write (Output, Ch)
Read(!nput,Ch)
Writeln(Output)
Rea dIn (Input)
Eot(!nput)
Eoln(!nput)
The following program shows the use of the standard file Lst to list the file
ProductFile (see the example on page 99 ) on the printer:
program ListProductFile;
const
MaXNumberOfProducts = 100;
type
ProductName = string[20];
Product = record
Va.r
Name: ProductName; IterrNumber: Integer;
InStock: Real;
Suppl ier: Integer;
end;
ProductFile: file of Product;
ProductRec: Product; I: Integer;
begin
Ass ign(ProductFi Ie, 'ffiOIXJCT. UI'A' ); Reset(ProductFi Ie);
for I := 1 to MaXNumberOfProducts do
begin
Read(ProductFile,ProductRec);
lJi th Produc tRec do
begin
if Name< >" then
end;
Writeln(Lst, 'Item: ',IterrNumber:5,' " Name:20,
From: " Supplier:5,
, Now in stock: ',InStock:0:0);
end;
Close(ProductFile);
end.
FILE TYPES
'05
14.6 Text File Input and Output
14.6 Text File Input and Output
Input and output of data in readable form is done through text files as descri-
bed in section 14.5. A text file may be assigned to any device, i.e. a disk file or
one of the standard I/O devices. Input and output on text files is done with the
standard procedures Read, Rea din, Write, and Writeln which use a special
syntax for their parameter lists to facilitate maximum flexibility of input and
output.
In particular, parameters may be of different types, in which case the I/O pro-
cedures provide automatic data conversion to and from the basic Char type of
text files.
If the first parameter of an I/O procedure is a variable identifier representing a
text file, then I/O will act on that file. If not, I/O will act on the standard files
Input and Output. See section 14.5.3 for more details.
14.6.1 Read Procedure
The Read procedure provides input of characters, strings, and numeric data.
The syntax of the Read statement is:
Read(Var1, Var2, ... , VarN)
or
Read(FiIVar, Var1, Var2, ... , VarN)
where Var1, Var2, ... , VarN are variables of type Char, String, Integer or Real. In
the first case, the variables are input from the the standard file Input, usually
the keyboard. In the second case, the variables are input from the text file
which is previously assigned to FilVar and prepared for reading.
With a variable of type Char, Read reads one character from the file and as-
signs that character to the variable. If the file is a disk file, Eoln is true if the
next character is a CR or a Ctrl-Z, and Eof is true if the next character is a Ctrl-
Z, or physical end-of-file is met. If the file is a logical device (including the
standard files Input and Output), Eoln is true if the character read was a CR or
if Eof is True, and Eof is true if the character read was a Ctrl-Z.
106 TURBO Pascal Language Manual
Read Procedure 14.6.1
With a variable of type string, Read reads as many characters as allowed by
the defined maximum length of the string, unless Eoln or Eat is reached first.
Eoln is true if the character read was a CR or if Eat is True, and Eat is true if
the last character read is a Ctrl-Z, or physical end-of-file is met.
With a numeric variable (Integer or Rea!), Read expects a string of characters
which complies with the format of a numeric constant of the relevant type as
defined in section 4.2. Any blanks, TABs, CRs, or LFs preceding the string are
skipped. The string must be no longer than 30 characters, and it must be fol-
lowed by a blank, a TAB, a CR, or a Ctrl-Z. If the string does not conform to
the expected format, an I/O error occurs. Otherwise the numeric string is con-
verted to a value of the appropriate type and assigned to the variable. When
reading from a disk file, and the input string is ended with a blank or a TAB,
the next Read or Readln will start with the character immediately following
that blank orTAB. For both disk files and logical devices, Eoln is true if the str-
ing was ended with a CR or a Ctrl-Z, and Eat is true if the string was ended
with a Ctrl-Z.
A special case of numeric input is when Eoln or Eat is true at the begin-
ning of the Read (e.g. if input from the keyboard is only a CR). In that case no
new value is assigned to the variable, and the variable retains its former value.
If the input file is assigned to the console device (CON:)' or if the standard file
Input is used in the {$B+} mode (default), special rules apply to the reading of
variables. On a call to Read or Readln, a line is input from the console and
stored into a buffer, and the reading of variables then uses this buffer as the
input source. This allows for editing during entry. The following editing facili-
ties are available: .
BACKSPACE and DEL.
Ctrl-X
Backspaces one character position and deletes the character there.
BACKSPACE is usually generated by pressing the key marked BS or
BACKSPACE or by pressing Ctrl-H. DEL is usually generated by the
key thus marked, or in some cases RUB or RUBOUT.
Backspaces to the beginning of the line and erases all characters in-
put.
The RETURN key is used to terminate the input line. This key may be marked
ENTER on some keyboards. This terminating CR is not echoed to the screen.
FILE TYPES 107
14.6.1 Read Procedure
Internally. the input line is stored with a Ctrl-Z appended to the end of it.
Thus. if fewer values are specified on the input line than the number of variab-
les in Reads parameter list. any Char variables in excess will be set to Ctrl-Z.
Strings will be empty. and numeric variables will remain unchanged.
The maximum number of characters that can be entered on an input line from
the console is 127 by default. However. you may lower this limit by assign-
ing an integer in the range 0 through 127 to the predefined variable BufLen.
Example:
Wri tee 'Fi Ie name (max. 14 chars): ,);
BufLen; = 14;
Read(Fi leName);
Notice that assignments to BufLen affect only the immediately following
Read. After that. BufLen is restored to 127.
14.6.2 Readln Procedure
The Readln procedure is identical to the Read procedure. except that after the
last variable has been read. the remainder of the line is skipped. I.e., all cha-
racters up to and including the next CR/LF sequence (or the next CR on a logi-
cal device) are skipped. The syntax of the procedure statement is:
Re a dIn (Var1. Var2 •...• VarN)
or
Re a dIn (Fil Var, Var1. Var2 •...• VarN)
After a Rea dIn • the following Read or Readln will read from the beginning of
the next line. Readln may also be called without parameters:
Readln
or
Readln(FiIVar)
in which case the remaining of the line is skipped. When Readln is reading
from the console (standard file Input or a file assigned to CON:). the terminat-
ing CR is echoed to the screen as a CR/LF sequence. as opposed to Read.
108 TURBO Pascal Language Manual
Write Procedure 14.6.3
14.6.3 Write Procedure
The Write procedure provides output of characters, strings, boolean values,
and numeric values. The syntax of a Write statement is:
Write(Var1, Var2, ... , VarN)
or
Write(FilVar, Var1, Var2, ... , VarN)
where Var1, Var2, ... , VarN (the write parameters) are variables of type Char,
String, Boolean, Integer or Real, optionally followed by a colon and an integer
expression defining the width of the output field. In the first case, the variab-
les are output to the the standard file Output, usually the screen. In the se-
cond case, the variables are output to the text file which is previously assig-
ned to FilVar.
The format of a write parameter depends on the type of the variable. In the
following descriptions of the different formats and their effects, the symbols:
I, m, n
R
Ch
S
B
Ch
Ch:n
S
S:n
B
B:n
I:n
denote expressions of type Integer,
denotes an expression of type Real,
denotes an expression of type Char,
denotes an expression of type String, and
denotes an expression of type Boolean.
The character Ch is output.
The character Ch is output right-adjusted in a field which is n charac-
ters wide, i.e. Ch is preceded by n -1 blanks.
The string S is output. Arrays of characters may also be output, as
they are compatible with strings.
The string S is output right-adjusted in a field which is n characters
wide, i.e. S is preceded by n -length(S) blanks.
Depending on the value of B, either the word TRUE or the word
FALSE is output.
Depending on the value of B, either the word TRUE or the word
FALSE is output right-adjusted in a field which is n characters wide.
The decimal representation of the value of I is output.
The decimal representation of the value of I is output right-adjusted in
a field which is n characters wide.
FILE TYPES 109
14.6.3 Write Procedure
R The decimal representation of the value of R is output, right adjusted
in a field 18 characters wide, using floating point format:
R >= 0.0: ~ . d d d d d d d d d ~ d d
R < 0.0: _ - d . d d d d d d d d d ~ d d
where ~ represents a blank, d represents a digit, and t represents eit-
her'+' or'-'.
R:n The decimal representation of the value of R is output, right adjusted
in a field n characters wide, using floating point format:
R >= 0.0: blanksd.digitsEtdd
R < 0.0: blanks-d.digitsEtdd
where blanks represents zero or more blanks, digits represents from
one to ten digits, d represents a digit, and t represents either p;us or
minus. As at least one digit is output after the decimal point, the field
width is minimum 7 characters (8 for R < 0.0). When n is greater than
16 (17 for R < 0.0), the number is preceded by n -16 blanks (n -17 for
R< 0.0).
R:n:m The decimal representation of the value of R is output, right adjusted
in a field n characters wide, using fixed point format with m digits af-
ter the decimal point. No decimal part, and no decimal point, is output
if m is O. m must be in the range 0 < = m < = 24; otherwise floating
point format is used. The number is preceded by an appropriate num-
ber of blanks to make the field width n.
110 TURBO Pascal Language Manual
Writeln Procedure 14.6.4
14.6.4 Writeln Procedure
The Writeln procedure is identical to the Write procedure, except that a CR/LF
sequence is output after the last value. The syntax of the Writeln statement is:
Writeln{Var1, WP2, ... , WPn)
or
Writeln{FiIVar, WP1, WP2, ... , WPn)
A Writeln with no write parameters outputs an empty line consisting of a
CR/LF sequence:
Writeln
or
Writeln{File)
FILE TYPES 111
14.7 Untyped Files
14.7 Untyped Files
Untyped files are low-level I/O channels primarily used for direct access to
any disk file using a record size of 128 bytes.
In input and output operations to untyped files, data is transferred directly
between the disk file and the variable, thus saving the space required by the
sector buffer required by typed files. An untyped file variable therefore occu-
pies less memory than other file variables. As an untyped file is furthermore
compatible with any file, the use of an untyped file is therefore to be preferred
if a file variable is required only for Erase, Rename or other non-input/output
operations.
An untyped file is declared with the reserved word file:
Var
DataFi Ie: fi Ie;
14.7.1 BlockRead / BlockWrite
All standard file handling procedures and functions except Read, Write, and
Flush are allowed on untyped files. Read and Write are replaced by two spe-
cial high-speed transfer procedures: BloekRead and BloekWrite. The syntax of
a call to these procedures is:
BlockRead( FilVar, Var, rees)
BlockWrite( FilVar, Var, rees)
where FilVar variable identifier of an untyped file, Var is any variable, and rees
is an integer expression defining the number of 128-byte records to be trans-
ferred between the disk file and the variable. The transfer starts at the first
byte occupied by the variable Var. The programmer must insure the program-
mer to insure that the variable Var occupies enough space to accomodate the
entire data transfer. A call to BloekRead or BloekWrite also advances the file
pointer rees records.
A file to be operated on by BloekRead or Block Write must first be prepared by
Assign and Rewrite or Reset. Rewrite creates and opens a new file, and Reset
opens an existing file. After processing, Close should be used to insure proper
termination.
712 TURBO Pascal Language Manual
BlockRead / Block Write 14.7..1
The standard function EOF works as with typed files. So do standard func-
tions FilePos and FileSize and standard procedure Seek, using a component
size of 128 bytes (the record size used by BlockRead and BlockWrite).
The following program shows the use of an untyped file. It reads any disk file
and copies its contents to any other disk file:
program Fi leCopy;
const
BufSize
BufByteSize
var
200;
15600;
Source,
Destination:
SourceName,
Fi Ie;
DestinationName: string[14];
Buffer: a r r ~ [ 1 .. BufByteSize] of Byte;
NoOfRecsToRead,
Remaining: Integer;
begin
Wri tee 'Enter source file name: ' );
Readln( SourceName);
Ass ign(Source, SourceName);
Reset (Source);
Write( 'Enter destination file name: ,);
Readln(DestinationName);
Assign(Dest inat ion, DestinationName);
Rewri te(Dest inat ion);
Remaining := FileSize(Source);
whi Ie Remaining > 0 do
begin
if BufSize <= Remaining then
NoOfRecsTaRead: =BufSize
else
NoOfRecsToRead: =Remaining;
B lockRead( Source, Buffer , NoOfRecsToRead) ;
BlockWrite(Destination,Buffer,NoOfRecsToRead);
Remaining : = Remaining-NoOfRecsToRead;
end;
Close(Dest inat ion);
end.
FILE TYPES 113
14.8 I/O checking
14.8 I/O checking
The I compiler directive is used to control generation of runtime I/O error
checking code. The default state is active, Le. {$I+} which causes calls to an
I/O check routine after each I/O operation. I/O errors then cause the program
to terminate, and an error message indicating the type of error is displayed.
If I/O checking is passive, Le. {$I-}, no run time checks are performed. An I/O
error thus does not cause the program to stop, but suspends any further I/O
until the standard function 10resuit is called. When this is done, the error con-
dition is reset and I/O may be performed again. It is now the programmer's
responsibility to take proper action according to the type of I/O error. A zero
returned by 10resuit indicates a successful operation, anything else means
that an error occurred during the last I/O operation. Appendix I lists all error
messages and their Numbers. Notice that as the error condition is reset
when 10resuit is called, subsequent calls to 10resuit will return zero until the
next I/O error occurs.
The 10result function is very convenient in situations where a program halt is
an unacceptaple result of an I/O error, like in the following example which
continues to ask for a file name until the attempt to reset the file is succesful
(Le. until an existing file name is entered):
procedure OpenInFi Ie;
begin
repeat
Write('Enter name of input file ,);
Readln( InFi leName);
AssignCInFile, InFi leName);
{$I-} ResetCInFile) {$I+} ;
OK : = CIOresul t = 0);
if not OK then Writeln('Cannot find file ',InFileName);
until OK;
end;
When the I directive is passive ({ $I-}), the following standard procedures
should be followed by a check of 10resuit to insure proper error handling:
Assign
BlockRead
BlockWri te
Chain
114
Close
E:<>ase
Execute
Flush
Read
Readln
Rename
Reset
Rewri te
Seek
Write
Wri teln
TURBO Pascal Language Manual
POINTER TYPES 15
15. IPODNTIEIR TYlPlES
Variables discussed up to now have been static, i.e. their form and size is pre-
determined, and they exist throughout the entire execution of the block in
which they are declared. Programs, however, frequently need the use of a
data structure which varies in form and size during execution. Dynamic va-
riables serve this purpose as they are generated as the need arises and may
be discarded after use.
Such dynamic variables are not declared in an explicit variable declaration like
static variables, and they cannot be referenced directly by identifiers. Instead,
a special variable containing the memory address of the variable is used to
point to the variable. This special variable is called a pointer variable.
15.1 Defining a Pointer Variable
A pointer type is defined by the pointer symbol succeeded by the type
identifier of the dynamic variables which may be referenced by pointer variab-
les of this type.
The following shows how to declare a record with associated pointers. The
type Person Pointer is is declared as a pointer to variables of type PersonRe-
cord:
type
PersonPointer =
PersotiRecord =
Var
Name: string[ 50];
Job: string[50];
Next: PersonPointer;
end;
FirstPerson, LastPerson, NewPerson: PersonPointer;
The variables NextPerson, LastPerson and NewPerson are thus pointer
variables which can point at records of type Person Record.
POINTER TYPES 115
15.1 Defining a Pointer Variable
As shown above, the type identifier in a pointer type definition may refer to an
identifier which is not yet defined.
15.2 Allocating Variables (New)
Before it makes any sense to use any of these pointer variables we must, of
course, have some variables to point at. New variables of any type are alloca-
ted with the standard procedure New. The procedure has one parameter
which must be a pointer to variables of the type we want to create.
A new variable of type PersonRecord can thus be created by the statement:
New(Fi rstPerson);
which has the effect c'f having FirstPerson point at a dynamically allocated re-
cord of type Person Record.
Assignments between pointer variables can be made as long as both pointers
are of identical type. Pointers of identical type may also be compared using
the relational operators = and <>, returning a Boolean result (True or False).
The pointer value nil is compatible with all pointer types. nil points to no dy-
namic variable, and may be aS,signed to pointer variables to indicate the ab-
sence of a usable pointer. nil may also be used in comparisons.
Variables created by the standard procedure New are stored in a stack-like
structure called the heap. The TURBO Pascal system controls the heap by
maintaining a heap pointer which at the beginning of a program is initialized
to the address of the first free byte in memory. On each call to New, the heap
pointer is moved towards the top of free memory the number of bytes corre-
sponding to the size of the new dynamic variable.
15.3 Mark and Release
When a dynamic variable is no longer required by the program, the standard
procedures Mark and Release is used to reclaim the memory allocated to
these variables. The Mark procedure assigns the value of the heap pointer to a
variable. The syntax of a call to Mark is:
Mark(Var);
116 TURBO Pascal Language Manual
Mark and Release 15.3
where Var is a pointer variable. The Release procedure sets the heap pointer
to the address contained in its argument. The syntax is:
Re 1 ease(Var);
where Var is a pointer variable, previously set by Mark. Release thus discards
all dynamic variables above this address. It is not possible to release the
space used by variables in the middle of the heap.
The standard function MemAvail is available to determine the available space
on the heap at any given time. Further discussion is deferred to appendices A
and B.
15.4 Using Pointers
Supposing we have used the New procedure to create a series of records of
type Person Record (as in the example on the following page) and that the
field Next in each record points at the next Person Record created, then the
following statements will go through the list and write the contents of each
record (FirstPerson points to the first person in the list):
_hi Ie FirstPerson <> nil do
with do
begin
Writeln(Name,' is a ',Job);
FirstPerson .- Next;
end;
FirstPersonA.Name may be read as FirstPerson's.Name, i.e. the field Name in
the record pointed to by FirstPerson.
The following demonstrates the use of pointers to maintain a list of names
and related job desires. Names and job desires will be read in until a blank
name is entered. Then the entire list is printed. Finally, the memory used by
the list is released for other use. The pointer variable Heap Top is used only for
the purpose of recording and storing the initial value of the heap pointer. Its
definition as a Integer (pointer to integer) is thus totally arbitrary.
POINTER TYPES 117
15.4
procedure Jobsj
type
PersonPointer =
PersonRecord = record
Var
Name: strin.g[50];
Job: strin.g[ 50];
Next: PersonPointerj
endj
HeapTop: Integerj
Using Pointers
FirstPerson, LastPerson, NewPerson: PersonPointerj
Name: strin.g[50] j
begin
Fi rstPerson : = ni 1;
Mark(HeapTop) ;
repeat
Wri tee 'Enter name: ' );
Readln(Name);
if Name <> " then
begfn
New(NewPerson) ;
. Name . - Name;
Write( 'Enter profession: ,);

Wri teln;
if FirstPerson = nil then
Fi rstPerson : = NewPerson
else
. Next : = NewPerson;
LastPerson : = NewPerson;
. Next : = ni 1;
end;
until Name = , ';
Wri telnj
while FirstPerson <> nil do
with do
begin
Write In(Name , ' is a ',Job);
FirstPerson := Next;
end;
Re lease(HeapTop) j
end.
118 TURBO Pascal Language Manual
Space Allocation 15.5
15.5 Space Allocation
The standard procedure GetMem is used to allocate space on the heap. Un-
like New, which allocates as much space as required by the type pointed to
by its argument, GetMem allows the programmer to control the amount of
space allocated. GetMem is called with two parameters:
GetMem(PVar, 1)
where PVar is any pointer variable, and I is an integer expression giving the
number of bytes to be allocated.
POINTER TYPES 119
15.5 Space Allocation
Notes:
120 TURBO Pascal Language Manual
PROCEDURES AND FUNCTIONS 16
16. PROCEDURES AND FUNCTIONS
A Pascal program consists of one or more blocks, each of which may again
consist of blocks, etc. One such block is a procedure, another is a function (in
common called subprograms). Thus, a procedure is a separate part of a pro-
gram, and it is activated from elsewhere in the program by a procedure state-
ment (see section 7.1.2). A function is rather similar, but it computes and re-
turns a value when its identifier, or designator, is encountered during execu-
tion (see section 6.2).
16.1 Parameters
Values may be passed to procedures and functions through parameters. Para-
meters provide a substitution mechanism which allows the logic of the sub-
program to be used with different initial values, thus producing different re-
sults.
The procedure statement or function designator which invokes the subpro-
gram may contain a list of parameters, called the actual parameters. These
are passed to the formal parameters specified in the subprogram heading. The
order of parameter passing is the order of appearance in the parameter lists.
Pascal supports two different methods of parameter passing: by value and by
reference, which determines the effect that changes of the formal parameters
have on the actual parameters.
When parameters are passed by value, the formal parameter represents a lo-
cal variable in the subprogram, and changes of the formal parameters have no
effect on the actual parameter. The actual parameter may be any expression,
including a variable, with the same type as the corresponding formal parame-
ter. Such parameters are called a value parameter and are declared in the
subprogram heading as in the following example. (This and the following ex-
amples show procedure headings; function headings are slightly different as
described i section 1 6.3.1 .)
procedure ExampleCNuml,Num2: Number; Strl,Str2: Txt);
Number and Txt are previously defined types (e.g. Integer and string[255]),
and Num1, Num2, Str1, and Str2 are the formal parameters to which the va-
lue of the actual parameters are passed. The types of the formal and the ac-
tual parameters must correspond.
PROCEDURES AND FUNCTIONS 121
16.1 Parameters
Notice that the type of the parameters in the parameter part must be speci-
fied as a previously defined type identifier. Thus, the construct:
procedure Select(Model: a r r ~ [ 1 .. 500] of Integer);
is not allowed. Instead, the desired type should be defined in the type defini-
tion of the block, and the type identifier should then be used in the parameter
declaration:
type
Range a r r ~ [ 1 .. 500] of Integer;
procedure Select(Model: Range);
When a parameter is passed by reference, the formal parameter in fact repre-
sents the actual parameter throughout the execution of the subprogram. Any
changes made to the formal parameter is thus made to the actual parameter,
which must therefore be a variable. Parameters passed by reference are cal-
led a variable parameters, and are declared as follows:
procedure Example(Var Numl ,Num2 : Number)
Value parameters and variable parameters may be mixed in the same proce-
dure as in the following example:
procedure Example(Var Num1,Num2: NUmber; Str1,Str2: Txt);
in which Num1 and Num2 are variable parameters and Stf1 and Str2 are va-
lue parameters.
All address calculations are done at the time of the procedure call. Thus, if a
variable is a component of an array, its index expression(s) are evaluated
when the subprogram is called.
Notice that file parameters must always be declared as variable parameters.
When a large data structure, such as an array, is to be passed to a subpro-
gram as a parameter, the use of a variable parameter will save both time and
storage space, as the only information then passed on to the subprogram is
the address of the actual parameter. A value parameter would require storage
for an extra copy of the entire data structure, and the time involved in copying
it.
122 TURBO Pascal Language Manual
Relaxations on Parameter Type Checking 16.1.1
16.1.1 Relaxations on Parameter Type Checking
Normally, when using variable parameters, the formal and the actual parame-
ters must match exactly. This means that subprograms employing variable
parameters of type String will accept only strings of the exact length defined
in the subprogram. This restriction may be overridden by the V compiler di-
rective. The default active state {$V+} indicates strict type checking, whereas
the passive state { $V -} relaxes the type checking and allows actual parame-
ters of any string length to be passed, irrespective of the length of the formal
parameters.
Example:
program NSA;
{this program must be compiled with the $V- directive}
{$V- }
type
WorkString = string[255];
Var
Line1: string[80];
Line2: string[ 100] ;
procedure Encode(Var LineToEncode: WorkString);
Var I: Integer;
begin
for I := 1 to Length(LineToEncode) do
LinetoEncode[I] := Chr(Ord(LineToEncode[I])-30);
end;
begin
Line1 .- 'This is a secret message';
Encode(Line1) ;
Line2 := 'Here is another (longer) secret message';
Enc ode (L ine2);
end.
16.1.2· Untyped Variable Parameters
If the type of a formal parameter is not defined, i.e. the type definition is omit-
ted from the parameter section of the subprogram heading, then that parame-
ter is said to be untyped. Thus, the corresponding actual parameter may be
any type.
PROCEDURES AND FUNCTIONS 123
16.1.2 Untyped Variable Parameters
The untyped formal parameter itself is incompatible with all types, and it may
therefore be used only in contexts where the data type is of no significance,
e.g. as a parameter to Addr, BlockRead/Write, Fil/Char, or Move, or as the ad-
dress specification of absolute variables.
The Switch Var procedure in the following example demonstrates the use of
untyped parameters. It moves the contents of the variable A1 to A2 and the
contents of A2 to A 1 .
procedure Swi tchVar(Var Alp,A2p; Size: Integer);
type
A = array[ 1. . MaxInt] of Byte;
Var
Al: A absolute Alp;
.AJ!,: A absolute A2p;
Tmp: Byte;
Count: Integer;
begin
for Count := 1 to Size do
begin
Tmp : = Al[ Count];
AI[ Count] . - A2[ Count] ;
A2[ Count] : = Tmp;
end;
end;
Assuming the declarations:
type
Matrix = arrayL1.. 50,1. .25] of Real;
Var
TestMatrix,BestMatrix: Matrix;
then Switch Var may be used to switch values between the two matrices:
SwitchVar(TestMatrix,BestMatrix, SizeOf(Matrix));
124 TURBO Pascal Language Manual
Procedures 16.2
16.2 Procedures
A procedure may be either pre-declared (or 'standard') or user-declared, i.e.
declared by the programmer. Pre-declared procedures are parts of the
TURBO Pascal system and may be called with no further declaration. A user-
declared procedure may be given the name of a standard procedure; but that
standard procedure then becomes inaccessible within the scope of the user
declared procedure.
16.2.1 Procedure Declaration
A procedure declaration consists of a procedure heading followed by a block
which consists of a declaration part and a statement part.
The procedure heading consists of the reserved word procedure followed by
an identifier which becomes the name of the procedure, optionailly followed
by a formal parameter list as described in section 16.1 .
Examples:
procedure Logon;
procedure Position(X,Y: Integer);
procedure Compute(Var Data: Matrix; Scale: Real);
The declaration part of a procedure has the same form as that of a program.
All identifiers declared in the formal parameter list and the declaration part
are local to that procedure, and to any procedures within it. This is called the
scope of an identifier, outside which they are not known. A procedure may
reference any constant, type, variable, procedure, or function defined in an
outer block.
The statement part specifies the action to be executed when the the proce-
dure is invoked, and it takes the form of a compound statement (see section
7.2.1). If the procedure identifier is used within the statement part of the pro-
cedure itself, the procedure will ex'ecute recursively. (CP/M -80 only: Notice
that the A compiler directive must be passive { $A-} when recursion is used,
see appendix E .)
The next example shows a program which uses a procedure and passes a pa-
rameter to this procedure. As the actual parameter passed to the procedure is
in some instances a constant (a simple expression), the formal parameter
must be a value parameter.
PROCEDURES AND FUNCTIONS 125
16.2.1
program Box;
Var
I: Integer;
procedure DrawBox(Xl ,Yl, X2, Y2: Integer);
Var I: Integer;
begin
GotoXY(Xl ,Yl);
for I := Xl to X2 do write('-');
GotoXY(Xl ,Yl+l);
f or I : = Yl + 1 to Y2 do
begin
GotoXY(Xl,1); Write('!');
GotoXY(X2,1); Write('!');
end;
GotoXY(Xl ,Y2);
for I := Xl to X2 do Write( ,-,);
end; { of procedure DrawBox }
begin
C lrScr;
Procedure Declaration
for I := 1 to 5 do DrawBox(I*4,I*2,10*I,4*I);
DrawBox(1,1,80,23);
end.
Often the changes made to the formal parameters in the procedure should
also affect the actual parameters. In such cases variable parameters are used,
as in the following example:
procedure Switch(Var A,B: Integer);
Var Tmp: Integer;
begin
Tmp . - A; A : = B; B . - Tmp;
end;
When this procedure is called by the statement:
Switch(I,J);
the values of I and J will be switched. If the procedure heading in Switch
was declared as:
procedure SWitch(A,B: Integer);
i.e. with a value parameter, then the statement Swi tch( I, J) would not
change I and J.
126 TURBO Pascal Language Manual
Standard Procedures 16.2.2
16.2.2 Standard Procedures
TURBO Pascal contains a number of standard procedures. These are:
1) string handling procedures (described in section 9.5),
2) file handling procedures (described in sections 14.2 , 14.5.1, and
14.7.1 .
3) procedures for allocation of dynamic variables (described in sections
15.2 and 15.5 ), and
4) input and output procedures (described in section 14.6).
In addition to these, the following standard procedures are available, provided
that the associated commands have been installed for your terminal (see sec-
tion 1.6):
16.2.2.1 ClrEol
Syntax: ClrEol
Clears all characters from the cursor position to the end of the line without
moving the cursor.
16.2.2.2 CIrScr
Syntax: ClrScr
Clears the screen and places the cursor in the upper left-hand corner. Beware
that some screens also reset the video-attributes when clearing the screen,
possibly disturbing any user-set attributes.
16.2.2.3 Crt Init
Syntax: Crtlnit
Sends the Terminal Initialization String defined in the installation procedure
to the screen.
PROCEDURES AND FUNCTIONS 127
16.2.2.4 Crt Exit
16.2.2.4 Crt Exit
Syntax: CrtExit
Sends the Terminal Reset String defined in the installation procedure to the
screen.
16.2.2.5 Delay
Syntax: Delay(Time)
The Delay procedure creates a loop which runs for approx. as many millise-
conds as defined by its argument Time which must be an integer. The exact
time may vary somewhat in different operating environments.
16.2.2.6 Delline
Syntax: DelLine
Deletes the line containing the cursor and moves all lines below one line up.
16.2.2.7 Ins line
Syntax: I nsLine
Inserts an empty line at the cursor position. All lines below are moved one line
down and the bottom line scrolls off the screen.
16.2.2.8 GotoXY
Syntax: GotoXY(Xpos, Ypos)
Moves the cursor to the position on the screen specified by the integer ex-
pressions Xpos (horizontal value, or row) and Ypos (vertical value, or column).
The upper left corner (home position) is (1,1).
128 TURBO Pascal Language Manual
LowVideo 16.2.2.9
16.2.2.9 LowVideo
Syntax: LowVideo
Sets the screen to the video attribute defined as 'Start of Low Video' in the in-
stallation procedure, i.e. 'dim' characters.
16.2.2.10 Norm Video
Syntax: NormVideo
Sets the screen to the video attribute defined as 'Start of Normal Video' in the
installation procedure, i.e. the 'normal' screen mode.
16.2.2.11 Randomize
Syntax: Randomize
Initializes the random number generator with a random value.
16.2.2.12 Move
Syntax: Move(var1,var2,Num}
Does a mass copy directly in memory of a specified number of bytes. var1 and
var2 are two variables of any type, and Num is an integer expression. The pro-
cedure copies a block of Num bytes, starting at the first byte occupied by var1
to the block starting at the first byte occupied by var2. You may notice the ab-
sence of explicit 'moveright' and 'moveleft' procedures. This is because Move
automatically handles possible overlap during the move process.
16.2.2.13 Fil/Char
Syntax: FiliChar(Var, Num, Value}
Fills a range of memory with a given value. Var is a variable of any type, Num
is an integer expression, and Value is an expression of type Byte or Char. Num
bytes, starting at the first byte occupied by Var, are filled with the value Value.
PROCEDURES AND FUNCTIONS 129
16.3 Functions
16.3 Functions
Like procedures, functions are either standard (pre-declared) or declared by
the programmer.
16.3.1 Function Declaration
A function declaration consists of a function heading and a block which is a
declaration part followed by a statement part.
The function heading is equivalent to the procedure heading, except that the
heading must define the type of the function result. This is done by adding a
colon and a type to the heading as shown here:
function KeyHit: Boolean;
function Compute(Var Value: Sample): Real;
function Power(X,Y: Real): Real;
The result type of a function must be a scalar type (i.e. Integer, Real, Boolean,
Char, declared scalar or subrange), a string type, or a pointer type.
The declaration part of a function is the same as that of a procedure.
The statement part of a function is a compound statement as described in
section 7.2.1. Within the statement part at least one statement assigning a
value to the function identifier must occur. The last assignment executed de-
termines the result of the function. If the function designator appears in the
statement part of the function itself, the function will be invoked recursively.
(CP/M-SO only: Notice that the A compiler directive must be passive {$A-}
when recursion is used, see appendix E .)
130 TURBO Pascal Language Manual
Function Declaration 16.3.1
The following example shows the use of a function to compute the sum of a
row of integers from I to J.
function RowSumCI,J: Integer): Integer;
function SimpleRowSum(S: Integer): Integer;
begin
SimpleRowSum := S*(S+l) div 2;
end;
begin
RowSum . - SimpleRowSum(J) -SimpleRowSum( I -1);
end;
The function SimpleRowSum is nested within the function RowSum.
SimpleRowSum is therefore only available within the scope of RowSum.
The following program is the classical demonstration of the use of a re-
cursive function to calculate the factorial of an integer number:
{$A- }
program Factorial;
Va.r Number: Integer;
function FactorialCValue: Integer): Real;
begin
if Value = 0 then Factorial := 1
else Factorial : = Value * FactorialCvalue-l);
end;
begin
Read(Number) ;
!
end.
',FactorialCNumber) );
Note that the type used in the definition of a function type must be previously
specified as a type identifier. Thus, the construct:
function LowCase(Line: UserLine): string[80];
is not allowed. Instead, a type identifier should be associated with the type
stringf80J, and that type identifier should then be used to define the function
result type, e.g.:
type
Str80 = string[ 80];
function LowCase(Line: UserLine): Str80;
PROCEDURES AND FUNCTIONS 131
16.3.1 Function Declaration
Because of the implementation of the standard procedures Write and Writeln,
a function using any of the standard procedures Read, Readln, Write, or Wri-
teln, must never be called by an expression within a Write or Writeln state-
ment. In 8-bit systems this is also true for the standard procedures Str and
Val.
16.3.2 Standard Functions
The following standard (pre-declared) functions are implemented in TURBO
Pascal:
1) string handling functions (described in section 9.5),
2) file handling functions (described in section 14.2 and 14.5.1 ), and
3) pointer related functions (described in sections 15.2 and 15.5 ).
16.3.2.1 Arithmetic Functions
16.3.2.1.1 Abs
Syntax: Abs( Num)
Returns the absolute value of Num. The argument Num must be either Real
or Integer, and the result is of the same type as the argument.
16.3.2.1.2 ArcTan
Syntax: ArcTan( Num)
Returns the angle, in radians, whose tangent is Num. The argument X must
be either Real or Integer, and the result is Real.
16.3.2.1.3 Cos
Syntax: Cos( Num)
Returns the cosine of Num. The argument Num is expressed in radians, and
its type must be either Real or Integer. The result is of type Real.
132 TURBO Pascal Language Manual
Cos 16.3.2.1.3
16.3.2.1.4 Exp
Syntax: Exp( Num)
Returns the exponential of Num, i.e. e
num
. The argument Num must be either
Real or Integer, and the result is Real.
16.3.2.1.5 Frac
Syntax: Frac( Num)
Returns the fractional part of Num, i.e. Frac( Num) = Num - Int( Num). The
argument Num must be either Real or Integer, and the result is Real.
16.3.2.1.6 Int
Syntax: Int( Num)
Returns the integer part of Num, i.e. the greatest integer number less than or
equal to Num, if Num ) = 0, or the smallest integer number greater than or
equal to Num, if Num < O. The argument Num must be either Real or Integer,
and the result is Real.
16.3.2.1.7 Ln
Syntax: Ln( Num)
Returns the natural logarithm of Num. The argument Num must be either
Real or Integer, and the result is Real.
16.3.2.1.8 Sin
Syntax: Sin( Num)
Returns the sine of Num. The argument Num is ~ x p r e s s e d in radians, and its
type must be either Real or Integer. The result is of type Real.
PROCEDURES AND FUNCTIONS 133
16.3.2.1.9 Sqr
16.3.2.1.9 Sqr
Syntax: Sqr( Num)
Returns the square of Num, i.e. N u m ~ Num. The argument Num must be eit-
her Real or Integer, and the result is of the same type as the argument.
16.3.2.1.10 Sqrt
Syntax: Sqrt( Num)
Returns the square root of Num. The argument Num must be either Real or
Integer, and the result is Real.
16.3.2.2 Scalar Functions
16.3.2.2.1 Pred
Syntax: Pred( Num)
Returns the predecessor of Num (if it exists). Num is of any scalar type.
16.3.2.2.2 Succ
Syntax: Succ( Num)
Returns the successor of Num (if it exists). Num is of any scalar type.
16.3.2.2.3 Odd
Syntax: Odd( Num)
Returns boolean True is Num is an odd number, and False if Num is even.
Num must be of type Integer.
134 TURBO Pascal Language Manual
Transfer Functions 16.3.2.3
16.3.2.3 Transfer Functions
The transfer functions are used to convert values of one scalar type to that of
another scalar type. In addition to the following functions, the retype facility
described in section 8.3 serves this purpose.
16.3.2.3.1 Chr
Syntax: Chr( Num)
Returns the character with the ordinal value given by the integer expression
Num. Example: Chr(65) returns the character 'A'.
16.3.2.3.2 Ord
Syntax: Ord( Var)
Returns the ordinal number of the value Var in the set defined by the type Var.
Ord{Var) is equivalent to Integer{Var) (see Type Conversiions in section 8.3 .
Var may be of any scalar type, except Real, and the result is of type Integer.
16.3.2.3.3 Round
Syntax: Round( Num)
Returns the value of Num rounded to the nearest integer as follows:
if Num > = 0, then Round{Num) = Trunc{Num + 0.5), and
if Num < 0, then Round{Num) = Trunc{Num - 0.5)
Num must be of type Real, and the result is of type Integer.
16.3.2.3.4 Trunc
Syntax: Trunc( Num)
Returns the greatest integer less than or equal to Num, if Num > = 0, or the
smallest integer greater than or equal to Num, if.,Num < O. Num must be of
type Real, and the result is of type Integer.
PROCEDURES AND FUNCTIONS 135
16.3.2.4 Miscellaneous Standard Functions
16.3.2.4 Miscellaneous Standard Functions
16.3.2.4.1 Hi
Syntax: Hi( t)
The low order byte of the result contains the high order byte of the value of
the integer expression I. The high order byte of the result is zero. The type of
the result is Integer
16.3.2.4.2 KeyPressed
Syntax: KeyPressed
Returns boolean True if a key has been pressed at the console, and False if no
key has been pressed. The result is obtained by calling the operating system
console status routine.
16.3.2.4.3 Lo
Syntax: Lo( t)
Returns the low order byte of the value of the integer expression I with the
high order byte forced to zero. The type of the result is Integer.
16.3.2.4.4 Random
Syntax: Random
Returns a random number greater than or equal to zero and less than one.
The type is Real.
16.3.2.4.5 Random( N um)
Syntax: Random( Num)
Returns a random number greater than or equal to zero and less than Num.
Num and the random number are both Integers.
136 TURBO Pascal Language Manual
Size Of 16.3.2.4.6
16.3.2.4.6 SizeOf
Syntax: SizeOf( Name)
Returns the number of bytes occupied in memory by the variable or type
Name. The result is of type Integer.
16.3.2.4.7 Swap
Syntax: Swap( Num)
The Swap function exchanges the high and low order bytes of its integer ar-
gument Num and returns the resulting value as an integer.
Example: Swap($1234) returns$3412 (values in hex for clarity).
16.3.2.4.8 UpCase
Syntax: UpCase( ch)
Returns the uppercase equivalent of its argument ch which must be of type
Char. If no uppercase equivalent exists, the argument is returned unchanged.
PROCEDURES AND FUNCTIONS 137
16.4 Forward References
16.4 Forward References
A subprogram is forward declared by specifying its heading separately from
the block. This separate subprogram heading is exactly as the normal head-
ing, except that it is terminated by the reserved word forward. The block fol-
lows later within the same declaration part. Notice that the block is initiated
by a copy of the heading, specifying only the name and no parameters, types,
etc.
Example:
program Catch22;
Var
X: Integer;
funct ion Up(Var I: Integer): Integer; forward;
funct ion Down(Var I: Integer): Integer;
begin
I := I div 2; Writeln(I);
if I <> 1 then I := Up(I);
end;
funct ion Up;
begin
while I mod. 2 <> 0 do
begin
I := 1*3+1; Writeln(1);
end;
I : = Down( 1) ;
end;
begin
Write( 'Enter any integer: ,);
Readln(X);
X := Up(X);
Write( 'Ok. Program stopped again. ,);
end.
When the program is executed and if you enter e.g. 6 it outputs:
138 TURBO Pascal Language Manual
Forward References
3
10
5
16
8
4
2
1
Ok. Program stopped again.
16.4
The above program is actually a more complicated version of the following
program:
program Catch222;
Var
X: Integer;
begin
Write( 'Enter any integer: ,);
Readln(X) ;
while X <> 1 do
begin
if X mod. 2 0 tben X .- X div 2 else X .- X*3+1;
Wri te In(X);
end;
Write( 'Ok. Program stopped again. ,);
end.
It may interest you to know that it cannot be proved if this small and very
simple program actually will stop for any integer!
PROCEDURES AND FUNCTIONS 139
16.4 Forward References
Notes:
140 TURBO Pascal Language Manual
INCLUDING FILES 17
17. INCLUDING FILES
The fact that the TURBO editor performs editing only within memory limits
the size of source code handled by the editor. The I compiler directive can be
used to circumvent this restriction, as it provides the ability to split the source
code into smaller 'lumps' and put it back together at compile-time. The in-
clude facility also aids program clarity, as commonly used subprograms, once
tested and debugged, may be kept as a 'library' of files from which the
necessary files can be included in any other program.
The syntax for the I compiler directive is:
{$I f i 1 ename }
where filename is any legal file name. Spaces are ignored and lower case let-
ters are translated to upper case. If no file type is specified, the default type
.PAS is assumed. This directive must be specified on a line by itself.
Exampes:
{$I firs t . pas}
{$i StdProc}
{$I COMPUTE. MOD}
To demonstrate the use of the include facility, let us assume that in your 'li-
brary' of commonly used procedures and functions you have a file called
STUPCASE.FUN. It contains the function StUpCase which is called with a
character or a string as parameter and returns the value of this parameter
with any lower case letters set to upper case.
File STUPCASE.FUN:
function StUp:Jase (St: AnyString): AnyString;
Var I: Integer;
begin
for I := 1 to Length(St) do
St[I] := Up:Jase(St[I]);
StUp:Jase : = St
end;
In any future program you write which requires this function to convert strings
to upper case letters, you need only include the file at compile-time instead of
duplicating it into the source code:
INCLUDING FILES 141
17
program Inc Iude Demo;
type
InData= string[ 80] ;
AnySt ring= string[ 255];
Var
Answer: InData;
{$I STUPCASE.FUN}
begin
ReadLn(Answer) ;
Wri te In(StUpCase(Answer));
end.
INCLUDING FILES
This method not only is easier and saves space; it also makes the task of
keeping programs updated quicker and safer, as any change to a 'library' rou-
tine will automatically affect all programs including this routine.
Notice that TURBO Pascal allows free ordering, and even multiple occur-
rences, of the individual sections of the declaration part. You may thus e.g.
have a number of files containing various commonly used type definitions in
your 'library' and include the ones required by different programs.
All compiler directives except Band C are local to the file in which they ap-
pear, i.e. if a compiler directive is set to a different value in an included file, it
is reset to its original value upon return to the including file. Band C directi-
ves are always global. Compiler directives are described in appendix E .
Include files cannot be nested, i.e. one include file cannot include yet another
file and then continue processing.
142 TURBO Pascal Language Manual
CP/M-80 A
A. CP/M-SO
This appendix describes features of TURBO Pascal specific to the 8-bit imple-
mentation. It presents two kinds of information:
1) Things you must know to make efficient use of TURBO Pascal. These are
described in section A.l .
2) The remaining sections describe things which are only of interest to expe-
rienced programmers, e.g. calling machine language routines, technical
aspects of the compiler, etc.
A.1 compiler Options
The 0 command selects the following menu on which you may view and
change some default values of the compiler. It also provides a helpful function
to find runtime errors in programs compiled into object code files.
compile -> Kemory
Com- fi Ie
cHn- fi Ie
Find run-time error Quit
Figure A-l : Options Menu
A.T.T Memory / Com file / cHn-file
The three commands M, C, and H select the compiler mode, i.e. where to put
the code which results from the compilation.
Memory is the default mode. When active, code is produced in memory and
resides there ready to be activated by a Run command.
CP/M-80 143
A.1.1 Memory / Com file / c Hn -file
Com-file is selected by pressing C. The arrow moves to point to this line.
When active, code is written to a file with the same name as the Work file (or
Main file, if specified) and the file type .COM. This file contains the program
code and Pascal runtime library, and may be activated by typing its name at
the console. Programs compiled this way may be larger than programs com-
piled in memory, as the program code itself does not take up memory during
compilation, and program code starts at a lower address.
cHain-file is selected by pressing H. The arrow moves to point to this line.
When active, code is written to a file with the same name as the Work file (or
Main file, if specified) and the file type .CHN. This file contains the program
code but no Pascal library and must be activated from another TURBO Pascal
program with the Chain procedure (see section A.1 0 ).
When Com or cHn mode is selected, the menu is expanded with the follow-
ing two lines:
Start address: XXXX (min YYYY)
End address: XXXX (max YYYY)
Figure A-2: Start and End Addresses
The use of these additional commands are explained in sections A.1.2 and
A.1.3.
A.I.2 Start Address
The Start address specifies the address (in hexadecimal) of the first byte of
the code. This is normally the end address of the Pascal library plus one, but
may be changed to a higher address if you want to set space aside e.g. for
absolute variables to be shared by a series of chained programs.
When you enter an 5, you are prompted to enter a new Start address. If you
just hit <RETURN>, the minimum value is assumed. Don't set the Start ad-
dress to anything less than the minimum value, as the code will then over-
write part of the Pascal library.
144 TURBO Pascal Language Manual
End Address A.l.3
A.l.3 End Address
The End address specifies the highest address available to the program (in
hexadecimal). The value in parentheses indicate the top of the TPA on your
computer, i.e. BOOS minus one. The default setting is 700 to 1000 bytes less
to allow space for the loader which resides just below BOOS when executing
programs from TURBO.
If compiled programs are to run in a different environment, the End address
may be changed to suit the TPA size of that system. If you anticipate your
programs to run on a range of different computers, it will be wise to set this
value relatively low, e.g. C1 00 (48K), or even A 100 (40K) if the program is to
run under MP/M.
When you enter an E, you are prompted to enter a End address. If you just hit
(RETURN), the default value is assumed (j.e. top of TPA less 700 to 1000
bytes). If you set the End address higher than this, the resulting programs
cannot be executed from TURBO, as they will overwrite the TURBO loader;
and if you set it higher than the TPA top, the resulting programs will over-
write part of BOOS if run on your machine.
A.l.4 Find Runtime Error
When you run a program compiled in memory, and a runtime error occurs, the
editor is invoked, and the error is automatically pointed out. This, of course, is
not possible if the program is in a .COM file or an .CHN file. Run time errors
then print out the error code and the value of the program counter at the time
of the error, e.g.:
Run-time error 01, PC=IB56
Program aborted
Figure A-3: Run-time Error Message
To find the place in the source text where the error occurred, enter the F com-
mand on the Options menu. When prompted for the address, enter the ad-
dress given by the error message:
CP/M-80 145
A.1A Find Runtime Error
Ent e r PC:-1B5.Q.
Figure A-4: Find Run-time Error
The place in the source text is now found and pointed out exactly as if the er-
ror had occurred while running the program in memory.
A.2 Standard Identifiers
The following standard identifiers are unique to the CP/M -80 implementa-
tion:
Bios
BiosHL_
Bdos
BdosHL
A.3 Absolute Variables
RecurPtr
StackPtr
Variables may be declared to reside at specific memory addresses, and are
then called absolute. This is done by adding the reserved word absolute and
an address expressed by an integer constant to the variable declaration.
Example:
var
IObyte: Byte absolute $0003;
CmdLine: string[127] absolute $80;
Absolute may also be used to declare a variable "on top" of another variab-
le, i.e. that a variable should start at the same address as another variable.
When absolute is followed by the variable (or parameter) identifier, the new
variable will start at the address of that variable (or parameter).
Example:
var
Str: string[32];
StrLen: Byte absolute Str;
146 TURBO Pascal Language Manual
Absolute Variables A.3
The above declaration specifies that the variable StrLen should start at the
same address as the variable Str, and since the first byte of a string variable
gives the length of the string, StrLen will contain the length of Str. Notice that
only one identifier may be specified in an absolute declaration, i.e. the cons-
truct
Identl, Ident2: Integer absolute $8008
is illegal. Further details on space allocation for variables are given in sections
A.1 5 and A.1 6 .
A.4 Addr Function
Syntax: Addr{ name)
Returns the address in memory of the first byte of the type, variable, pro-
cedure, or function with the identifier name. If name is an array, it may be
subscribed, and if name is a record, specific fields may be selected. The value
returned is of type Integer.
A.S Predefined Arrays
TURBO Pascal offers two predefined arrays of type Byte, called Mem and
Port, which are used to directly access CPU memory and data ports.
A.5.1 Mem Array
The predeclared array Mem is used to access memory. Each component of
the array is a Byte, and indexes correspond to addresses in memory. The in-
dex type is Integer. When a value is assigned to a component of Mem, it is
stored at the address given by the index expression. When the Mem array is
used in an expression, the byte at the address specified by the index is used.
Example:
Mem[WsCursor] . - 2;
Mem[WsCursor+l1 := $lB;
Mem[WsCursor+2] : = Orde' -, );
IObyte : = Mem[ 3];
Mem[Addr+Of f set] : = Mem[Addr];
CP/M-80 147
A.5.2 Port Array
A.5.2 Port Array
The Port array is used to access the data ports of the Z-80 CPU. Each ele-
ment of the array represents a data port with indexes corresponding to port
numbers. As data ports are selected by 8-bit addresses, the index type is
Byte. When a value is assigned to a component of Port, it is output to the port
specified. When a component of Port is referenced in an expression, its value
is input from the port specified.
The use of the port array is restricted to assignment and reference in ex-
pressions only, i.e. components of Port cannot function as variable parame-
ters to procedures and functions. Furthermore, operations referring to the en-
tire Port array (reference without index) are not allowed.
A.6 Array Subscript Optimization
The X compiler directive allows the programmer to select whether array sub-
scription should be optimized with regard to execution speed or to code size.
The default mode is active, i.e. {$X+l, which causes execution speed op-
timization. When passive, i.e. {$X-l, the code size is minimized.
A.7 With Statements
The default 'depth' of nesting of With statements is 2, but the W direrctive
may be used to change this value to between 0 and 9. For each block, With
statements require two bytes of storage for each nesting level allowed. Keep-
ing the nesting to a minimum may thus greatly afftect the size of the data
area in programs with many subprograms.
A.8 Pointer Related Items
A.B.t MemAvail
The standard function MemAvail is available to determine the available space
on the heap at any given time. The result is an Integer, and if more than
32767 bytes is available, MemAvail returns a negative number. The correct
number of free bytes is then calculated as 65536.0 + MemAvail. Notice the
use of a real constant to generate a Real result, as the result is greater than
GMaxlnt. Memory management is discussed in further detail in section A.16 .
148 TURBO Pascal Language Manual
Pointers and Integers A.B.2
A.B.2 Pointers and Integers
The standard functions Ord and Per provide direct control of the address con-
tained in a pointer. Ord returns the address contained in its pointer argument
as an Integer, and Per converts its Integer argument into a pointer which is
compatible with all pointer types.
These functions are extremely valuable in the hands of an experienced pro-
grammer as they allow a pointer to point to anywhere in memory. If used ca-
relessly, however, they are very dangerous, as a dynamic variable may be
made to overwrite other variables, or even program code.
A.9 External Subprograms
The reserved word external is used to declare external procedures and func-
tions, typically procedures and functions written in machine code.
An external subprogram has no block, i.e. no declaration part and no state-
ment part. Only the subprogram heading is specified, immediately followed by
the reserved word external and an integer constant defining the memory ad-
dress of the subprogram:
procedure DiskReset; external $EC00;
function IOstatus: boolean; external $0123
Parameters may be passed to external subprograms, and the syntax is exactly
the same as that of calls to ordinary procedures and functions:
procedure Plot(X,Y: Integer); external $F003;
procedure QuickSort(var List: PartNo); external $lC00;
Parameter passing to external subprograms is discussed further in section A.-
15.3.
A.10 Chain and Execute
TURBO Pascal provides two standard procedures: Chain and Execute which
allow you to activate other programs from a TURBO program. The syntax of
these procedure calls is:
Chain(Fi lVar)
Execute (Fi lVar)
CP/M-BO 149
A.10 Chain and Execute
where FilVar is a file variable of any type, previously assigned to a disk file
with the standard procedure Assign. If the file exists, it is loaded into memory
and executed.
The Chain procedure is used only to activate special TURBO Pascal .CHN fi-
les, i.e. files compiled with the cH n-file option selected on the Options menu
(see section A.1.1 ). Such a file contains only program code; no Pascal library.
It is loaded into memory and executed at the start address of the current pro-
gram, i.e. the address specified when the current program was compiled. It
then uses the Pascal library already present in memory. Thus, the current pro-
gram and the chained program must use the same start address.
The Execute procedure may be used to execute any .COM file, i.e. any file
containing executable code. This could be a file created by TURBO Pascal
with the Com-option selected on the Options menu (see section A.1.1 ). The
file is loaded and executed at address $1 00, as specified by the CP/M stan-
dard.
If the disk file does not exist, an I/O error occurs. This error is treated as de-
scri-bed in section 14.8 . If the I compiler directive is passive ({ $I-}), program
execution continues with the statement following the failed Chain or Execute
statement, and the IOresult function must be called prior to further I/O.
Data can be transferred from the current program to the chained program ei-
ther by shared global variables or by absolute address variables.
To insure overlapping, shared global variables should be declared as the very
first variables in both programs, and they must be listed in the same order in
both declarations. Furthermore, both programs must be compiled to the same
memory size (see section A.1.3 ). When these conditions are satisfied, the va-
riables will be placed at the same address in memory by both programs, and
as TURBO Pascal does not automatically initialize its variables, they may be
shared.
150 TURBO Pascal Language Manual
Chain and Execute
Example:
Program MAIN. COM:
program Main;
var
Txt:
CntPrg:
begin
string[ 80] ;
file;
Wri tee 'Enter any text: ,); Readln(Txt);
As s i gn( CntPrg, 'ChrCount . chn' ) ;
Chain(CntPrg) ;
end.
Program CHRCOUNT.CHN:
program ChrCount;
var
Txt: string[ 80] ;
NoOfChar,
NoOfUpc,
I: Integer;
begin
NoOfUpc . - 0;
N 00 fChar : = Lengt h( Txt) ;
for I := 1 to length(Txt) do
A.10
if Txt [I] in [ 'A' .. 'Z'] tben NoOfUpc . - Succ(NoOfUpc);
Wri tee 'No of characters in entry: ',NoOfChar);
Writeln( '. No of upper case characters: " NoOfUpc, '. ,);
end.
Note that neither Chain nor Execute can be used in direct mode, i.e. from a
program run with the compiler options switch in position Memory (section
A.1.1 ).
A program can determine whether it was invoked by Chain or Execute byexa-
mining the value of the byte at address $80 (which normally contains the
length of the CP/M command line). If this byte is $FF (255), the program was
activated by Chain or Execute, otherwise it was activated from the operating
system. Care should be taken if executing non-TURBO programs that they do
not use the CP/M command line when invoked, as the $FF value in address
$80 may otherwise cause confusion.
CP/M-80 151
A.11 In -line Machine Code
A.11 In-line Machine Code
TURBO Pascal features the inline statements as a very convenient way of in-
serting machine code instructions directly into the program text. An inline sta-
tement consists of the reset:Ved word inline followed by one or more con-
stants, variable identifiers, or location counter references, separated by slash-
es and enclosed in parentheses.
The constants may be either literal constants or constant identifiers, and they
must be of type Integer. Literals generate one byte of code if within the range
0 .. 255 ($00 .. $FF). otherwise two bytes in the standard byte reversed format.
Constant identifiers always generate two bytes of code.
A variable identifier generates two bytes of code (in byte reversed format)
containing the memory address of the variable.
A location counter reference consists of an asterisk, optionally followed by an
offset consisting of a plus or a minus sign and an integer constant. An aste-
risk alone generates two bytes of code (in byte reversed format) containing
the current location counter value. If the asterisk is followed by an offset, it is
added or subtracted before coding the address.
The following example of an inline statement generates machine code that
will convert all characters in its string argument to upper case.
procedure UpperCase(va.r Strg: Str); {Str is type String[255] }
begin
inline ($2AjStrg/
{
LD HL, (Strg)
}
$46/
{
LD B, (HL)
}
$04/
{
INC B
}
$05/
{
Ll: DED B
}
$CA!*+20/
{
JP Z,L2
}
$23/
{
INC HL
}
$7E/
{
LD A, (HL)
}
$FE/$61/
{
CF 'a'
}
$DAi*-9/
{
JP C,L1
}
$FE/$7B/
{
CF 'z'+l
}
$02/*-14/
{
JP NC,L1
}
$06/$20/
{
SUB 20H
}
$77/
{
LD (HL) ,A
}
$03/*-20);
{
JP L1
}
{
L2:
EXtU
$
}
end;
152 TURBO Pascal Language Manual
In -line Machine Code A.11
Inline statements may be freely mixed with other statements throughout the
statement part of a block, and inline statements may use all CPU registers.
Note, however, that the contents of the stack pointer register (SP) must be
the same on exit as on entry.
A.12 CP/M Function Calls
For the purpose of calling CP/M BOOS and BIOS routines, TURBO Pascal
introduces two standard procedures: Bdos and Bios, and four standard func-
tions: Bdos, BdosHL, Bios, and BiosHL.
Details on BOOS and BIOS routines are found in the CP/M Operating System
Manual published by Digital Research.
A.1 2.1 Bdos procedure and function
Syntax: Bdos( Func {, Param } )
The Bdos procedure is used to invoke CP/M BOOS routines. Func and Pa-
ram are integer expressions. Func denotes the number of the called routine
and is loaded into the C register. Param is optional and denotes a parameter
which is loaded into the DE register pair. A call to address 5 then invokes the
BOOS.
The Bdos function is called like the procedure and returns an Integer result
which is the value returned by the BOOS in the A register.
A.12.2 BdosHL function
Syntax: BdosHL( Func {, Param } )
This function is exactly similar to the Bdos function above, except that the re-
sult is the value returned in the H L register pair.
CP/M-80 153
A.T 2.3 Bios procedure and function
A.1 2.3 Bios procedure and function
Syntax: 8 ios(Func {, Param } )
The Bios procedure is used to invoke 810S routines. Func and Param are in-
teger expressions. Func denotes the number of the called routine, with 0
meaning the W800T routine, 1 the CONST routine, etc. I.e. the address of
the called routine is Func * 3 plus the W800T address contained in address-
es 1 and 2. Param is optional and denotes a parameter which is loaded into
the 8C register pair prior to the call.
The Bios function is called like the procedure and returns an integer result
which is the value returned by the 8 lOS in the A register.
A.12.4 BiosHL function
Syntax: 8iosHL(Func (, Param })
This function is exactly similar to the Bios function above, except that the re-
sult is the value returned in the HL register pair.
154 TURBO Pascal Language Manual
User Written I/O Drivers A.13
A.13 User Written I/O Drivers
For some applications it is practical for a programmer to define his own input
and output drivers, i.e. routines which perform input and output of characters
to and from external devices. The following drivers are part of the TURBO
environment, and used by the standard I/O drivers (although they are not
available as standard procedures or functions):
function ConSt: boolean;
function Conln: Char;
procedure ConOut(Ch: Char);
procedure LstOut(Ch: Char);
procedureAuxOut(Ch: Char);
function Auxin : Char;
procedure UsrOut(Ch: Char);
function Usrln: Char;
The ConSt routine is called by the function KeyPressed, the Conln and Con-
Out routines are used by the CON:, TRM:, and KBD: devices, the LstOut rou-
tine is used by the LST: device, the AuxOut and Auxin routines are used by
the AUX: device, and the UsrOut and Usrln routines are used by the USR: de-
vice.
By default, these drivers use the corresponding BIOS entry points of the
CP/M operating system, i.e. ConSt uses CONST, Conln uses CONIN, ConOut
uses CONOUT, LstOut uses LIST, AuxOut uses PUNCH, Auxin uses READER,
UsrOut uses CONOUT, and Usrln uses CONIN. This, however, may be chan-
ged by the programmer by assigning the address of a self-defined driver pro-
cedure or a driver function to one of the following standard variables:
Variable
ConStPtr
ConlnPtr
ConOutPtr
LstOutPtr
AuxOutPtr
AuxlnPtr
UsrOutPtr
UsrlnPtr
Contains the address of the
ConSt function
Conln function
Con Out procedure
LstOut procedure
AuxOut procedure
Auxin function
UsrOut procedure
Usrln function
A user defined driver procedure or driver function must match the definitions
given above, i.e. a ConSt driver must be a Boolean function, a Conln driver
must be a Char function, etc.
CP/M-80 155
A.14 Interrupt Handling
A.14 Interrupt Handling
The TURBO Pascal run time package and the code generated by the compiler
are both fully interruptible. Interrupt service routines must preserve all regi-
sters used.
If required, interrupt service procedures may be written in Pascal. Such proce-
dures should always be compiled with the A compiler directive active ({$A+})'
they must not have parameters, and they must themselves insure that all re-
gisters used are preserved. This is done by placing an inline statement with
the necessary PUSH instructions at the very beginning of the procedure, and
another inline statement with the corresponding POP instructions at the very
end of the procedure. The last instruction of the ending inline statement
should be an EI instruction ($FB) to enable further interrupts. If daisy chained
interrupts are used, the inline statement may also specify a RETI instruction (
$EO, $40), which will override the RET instruction generated by the compiler.
The general rules for register usage are that integer operations use only the
AF, BC, DE, and HL registers, other operations may use IX and IY, and real
operations use the alternate registers.
An interrupt service procedure should not employ any I/O operations using
the standard procedures and functions of TURBO Pascal, as these routines
are not re-entrant. Also note that BOOS calls (and in some instances BIOS
calls, depending on the specific CP/M implementation) should not be per-
formed from interrupt handlers, as these routines are not re-entrant.
The programmer may disable and enable interrupts throughout a program us-
ing 01 and EI instructions generated by inline statements.
If mode 0 (1M 0) or mode 1 (1M 1) interrupts are employed, it is the responsi-
bility of the programmer to initialize the restart locations in the base page
(note that RST 0 cannot be used, as CP/M uses locations 0 through 7). If
mode 2 (1M 2) interrupts are employed, the programmer should generate an
initialized jump table (an array of integers) at an absolute address, and initia-
lize the I register through a inline statement at the beginning of the program.
156 TURBO Pascal Language Manual
Internal Data Formats A.15
A.15 I nternal Data Formats
In the following descriptions, the symbol @ denotes the address of the first
byte occupied by a variable of the given type. The standard function Addr may
be used to obtain this value for any variable.
A.15.1 Basic Data Types
The basic data types may be grouped into structures (arrays, records, and disk
files), but this structuring will not affect their internal formats.
A.15.T.T Scalars
The following scalars are all stored in a single byte: Integer subranges with
both bounds in the range 0 .. 255, Booleans, Chars, and declared scalars with
less than 256 possible values. This byte contains the ordinal value of the va-
riable.
The following scalars are all stored in two bytes: Integers, Integer subranges
with one or both bounds not within the range 0 .. 255, and declared scalars
with more than 256 possible values. These bytes contain a 2's complement
16-bit value with the least significant byte stored first.
A.15.T.2 Reals
Reals occupy 6 bytes, giving a floating point value with a 40-bit mantissa and
an 8-bit 2's exponent. The exponent is stored in the first byte and the man-
tissa in the next five bytes which the least significant byte first:
@ Exponent
@ + 1 LSB of mantissa
@ +5 MSB of mantissa
The exponent uses binary format with an offset of $80. Hence, an exponent
of $84 indicates that the value of the mantissa is to be multiplied by 2 ft ($84-
$80) = 2 ft 4 = 16. If the exponent is zero, the floating point value is conside-
red to be zero.
CP/M-80 157
A.15.1.2 Reals
The value of the mantissa is obtained by dividing the 40-bit unsigned integer
by 2 A 40. The mantissa is always normalized, i.e. the most significant bit (bit 7
of the fifth byte) should be interpreted as a 1. The sign of the mantissa is sto-
red in this bit, a 1 indicating that the number is negative, and a 0 indicating
that the number is positive.
A.15.1.3 Strings
A string occupies the number of bytes corresponding to one plus the maxi-
mum length of the string. The first byte contains the current length of the str-
ing. The following bytes contain the actual characters, with the first character
stored at the lowest address. In the table shown below, L denotes the current
length of the string, and Max denotes the maximum length:
@
@ +1
@+2
@ +L
@ +L+1
@+Max
A.15.1.4 Sets
Current length (L)
First character
Second character
Last character
Unused
Unused
An element in a set occupies one bit, and as the maximum number of ele-
ments in a set is 256, a set variable will never occupy more than 32 bytes
(256/8).
If a set contains less than 256 elements, some of the bits are bound to be
zero at all times and need therefore not be stored. In terms of memory effi-
ciency, the best way to store a set variable of a given type would then be to
"cut off" all insignificant bits, and rotate the remaining bits so that the first
element of the set would occupy the first bit of the first byte. Such rotate ope-
rations, however, are quite slow, and TURBO therefore employs a compro-
mise: Only bytes which are statically zero (Le. by'tes of which no bits are used)
are not stored. This method of compression is very fast and in most cases as
memory efficient as the rotation method.
158 TURBO Pascal Language Manual
Sets A.15.1.4
The number of bytes occupied by a set variable is calculated as (Max div 8) -
(Min div 8) + 1, where Max and Min are the upper and lower bounds of the
base type of that set. The memory address of a specific element E is:
MemAddress = @ + (E div 8) - (Min div 8)
and the bit address within the byte at MemAddress is:
BitAddress = E mod 8
where E denotes the ordinal value of the element.
A.15.1.5 File Interface Blocks
Each file variable in a program has an associated file interface block (FIB). An
FIB occupies 176 bytes of memory and is divided into two sections: The con-
trol section (the first 48 bytes), and the sector buffer (the last 128 bytes). The
control section contains various information on the disk file or device cur-
rently assigned to the file. The sector buffer is used to buffer input and output
from and to the disk file.
The table below shows the format of an FIB:
@
@ +1
@+2
@+3
@+4
@+5
@+6
@+7
@+8
@+9
@ +10
@ +11
@ +12
@ +47
@+48
@ +175
CP/M-80
Flags byte
File type
Character buffer
Sector buffer pointer
Number of records (LSB)
Number of records (MSB)
Record length in bytes (LSB)
Record length in bytes (MSB)
Current record number (LSB)
Current record number (MSB)
Unused (reserved)
Unused (reserved)
First byte of CP/M FCB
Last byte of CP/M FCB
First byte of sector buffer
Last byte of sector buffer
159
A.15.1.5 File Interface Blocks
The flags byte at @ contains four one bit flags which indicate the current sta-
tus of the file:
bit 0 Input flag. High if input is allowed.
bit 1 Output flag. High if output is allowed.
bit 2 Write semaphore. High if data has been written to the
sector buffer.
bit 3 Read semaphore. High if the contents of the sector buffer
is undefined.
The file type field at@ +1 specifies the type of device currently assigned to the
file variable. The following values can occur:
o
1
2
3
4
5
6
The console device (CON:)
The terminal device (TRM:)
The keyboard device (KBD:)
The list device (LST:)
The auxiliary device (AUX:)
The user device (USR:)
A disk file
When a file is assigned to a logical device, only the first three bytes of the FIB
are of significance.
The sector buffer pointer at@ +3 contains an offset from the first byte of the
sector buffer. The following three fields are used only by random access files
(defined files) and untyped files. Each field consists of two bytes in byte rever-
sed format. Bytes@ +10 and@ +11 are currently unused, but reserved for fu-
ture expansion. Bytes@ +12 through@ +47 contain a CP/M file control block
(FCB). The last block of the FIB is the sector buffer used for buffering input
and output from and to disk files.
The FIB format described above applies to all defined files and textfiles. The
FIB of an untyped file has no sector buffer, as data is transferred directly be-
tween a variable and the disk file. Thus, the length of the FIB of an untyped
file is only 48 bytes.
A.1S.1.6 Pointers
A pointer consists of two bytes containing a 16-bit memory address, and it is
stored in memory using byte reversed format, i.e. the least significant byte is
stored first. The value nil corresponds to a zero word.
160 TURBO Pascal Language Manual
Data Structures A.15.2
A.15.2 Data Structures
Data structures are built from the basic data types using various structuring
methods. Three different structuring methods exist: arrays, records, and disk
files. The structuring of data does not in any way affect the internal formats of
the basic data types.
A.15.2.1 Arrays
The components with the lowest index values are stored at the lowest me-
mory address. A multi-dimensional array is stored with the rightmost dimen-
sion increasing first, e.g. given the array
Board: a r r ~ [ I .. 8,1 .. 8] of Square
you have the following memory layout of its components:
lowest address: Board!1,11
Board!1,21
Board!1,81
Board!2,11
Board!2,21
Highest address: Board!8,81
A.15.2.2 Records
The first field of a record is stored at the lowest memory address. If the record
contains no variant parts, the length is given by the sum of the lengths of the
individual fields. If a record contains a variant, the total number of bytes occu-
pied by the record is given by the length of the fixed part plus the length of
largest of its variant parts. Each variant starts at the same memory address.
CP/M-80 161
A.15.2.3 Disk Files
A.15.2.3 Disk Files
Disk files are different from other data structures in that data is not stored in
internal memory but in a file on an external device. A disk file is controlled th-
rough a file interface block (FIB) as described in section A.15.1.5. In general
there are two different types of disk files: random access files and text files.
A.15.2.3.1 Random Access Files
A random access file consists of a sequence of records, all of the same length
and same internal format. To optimize file storage capacity, the records of a
file are totally contiguous. The first four bytes of the first sector of a file con-
tains the number of records in the file and the length of each record in bytes.
The first record of the file is stored starting at the fourth byte.
sector 0, byte 0:
sector 0, byte 1 :
sector 0, byte 2:
sector 0, byte 3:
A.15.2.3.2 Text Files
Number of records (LSB)
Number of records (MSB)
Record length (LSB)
Record length (MSB)
The basic components of a text file are characters, but a text file is subdivided
into lines. Each line consists of any number of characters ended by a CR/LF
sequence (ASCII $OD/$OA). The file is terminated by a Ctrl-Z (ASCII $1 B).
A.15.3 Parameters
Parameters are transferred to procedures and functions via the Z-80 stack.
Normally, this is of no interest to the programmer, as the machine code gene-
rated by TURBO Pascal will automatically PUSH parameters onto the stack
before a call, and POP them at the beginning of the subprogram. However, if
the programmer wishes to use external subprograms, these must POP the
parameters from the stack themselves.
162 TURBO Pascal Language Manual
Parameters A.15.3
On entry to an external subroutine, the top of the stack always contains the
return address (a word). The parameters, if any, are located below the return
address, i.e. at higher addresses on the stack. Therefore, to access the para-
meters, the subroutine must first POP off the return address, then all the pa-
rameters, and finally it must restore the return address by PUSHing it back
onto the stack.
A.15.3.1 Variable Parameters
With a variable (VAR) parameter, a word is transferred on the stack giving the
absolute memory address of the first byte occupied by the actual parameter.
A.15.3.2 Value Parameters
With value parameters, the data transferred on the stack depends upon the
type of the parameter as described in the following sections.
A.1S.3.2.1 Scalars
Integers, Booleans, Chars and declared scalars (i.e. all scalars except Reals)
are transferred on the stack as a word. If the variable occupies only one byte
when it is stored, the most significant byte of the parameter is zero. Normally,
a word is POPped off the stack using an instruction like POP HL.
A.1S.3.2.2 Reals
A real is transferred on the stack using six bytes. If these bytes are POPped
using the instruction sequence:
IDP HL
IDP DE
IDP BC
then L will contain the exponent, H the fifth (least significant) byte of the
mantissa , E the fourth byte, 0 the third byte, C the second byte, and B the
first (most significant) byte.
CP/M-80 163
A.15.3.2.3 Strings
A.1S.3.2.3 Strings
When a string is at the top of the stack, the byte pointed to by SP contains the
length of the string. The bytes at addresses SP+1 through SP+n (where n is
the length of the string) contain the string with the first character stored at the
lowest address. The following machine code instructions may be used to POP
the string at the top of the stack and store it in StrBuf
ill DE,StrBuf
ill HL,0
ill B,H
ADD HL,SP
ill C, (HL)
INC 00
illIR
ill SP,HL
A.1S.3.2.4 Sets
A set always occupies 32 bytes on the stack (set compression only applies to
the loading and storing of sets). The following machine code instructions may
be used to POP the set at the top of the stack and store it in SetBuf
ill DE, SetBuf
ill HL,0
ADD HL,SP
ill 00,32
illIR
ill SP,HL
This will store the least significant byte of the set at the lowest address in
SetBuf
A.1S.3.2.S Pointers
A pointer value is transferred on the stack as a word containin the memory
address of a dynamic variable. The value NIL corresponds to a zero word.
164 TURBO Pascal Language Manual
Arrays and Records A.15.3.2.6
A.1S.3.2.6 Arrays and Records
Even when used as value parameters, Array and Record parameters are not
actually PUSHed onto the stack. Instead, a word containing the address of
the first byte of the parameter is transferred. It is then the responsibility of the
subroutine to POP this word, and use it as the source address in a block copy
operation.
A.15.4 Function Results
User written external functions must return their results exactly as specified
in the following:
Values of scalar types, except Reals, must be returned in the H L register pair.
If the type of the result is expressed in one byte, then it must be returned in L
and H must by zero.
Reals must be returned in the BC, DE, and HL register pairs. B, C, 0, E, and H
must contain the mantissa (most significant byte in B), and L must contain the
exponent.
Strings and sets must be returned on the top of the stack on the formats
described in sections A.1 5.3.2.3 and A.1 5.3.2.4.
Pointer values must be returned in the HL register pair.
CP/M-80 165
A.16 Memory Management
A.1 6 Memory Management
A.16.1 Memory Maps
The following diagrams illustrate the contents of memory at different stages
of working with the TURBO system. Solid lines indicate fixed boundaries (i.e.
determined by amount of memory, size of your CP/M, version of TURBO,
etc.), whereas dotted lines indicate boundaries which are determined at run-
time (e.g. by the size of the source text, and by possible user manipulation of
various pointers, etc.). The sizes of the segments in the diagrams do not ne-
cessarily reflect the amounts of memory actually consumed.
A.16.1.1 Compilation in Memory
During compilation of a program in memory (Memory-mode on compiler Op-
tions menu, see section A.1 ), the memory is mapped as follows:
- - - - - - - -- - - - - - - - - - - - - - - - ---
- -- -- - - - -- - - - - - -.- - - - - - - - - -
~
i
i
0000
CP/M and run-time workspace
Pascal Library
Turbo interface, editor, and compiler
Error messages, optional
Source text
Object code growing upward
Symbol table growing downward
CPU stack growing downward
CP/M
HighMem
Figure A-5: Memory map during compilation in memorv
166 TURBO Pascal Language Manual
Compilation in Memory A.16.1.1
If the error message file is not loaded when starting TURBO, the source text
starts that much lower in memory. When the compiler is invoked, it generates
object code working upwards from the end of the source text. The CPU stack
works downwards from the logical top of memory, and the compiler's symbol
table works downwards from an address 1 K ($400 bytes) below the logical
top of memory.
A.16.1.2 Compilation To Disk
During compilation to a .COM or .CHN file (Com-mode or cHn-mode on
compiler Options menu, see section A.1 ), the memory looks much as during
compilation in memory (see preceding section) except that generated object
code does not reside in memory but is written to a disk file. Also, the code
starts at a lower address (right after the Pascal library instead of after the
source text). Compilation of much larger 'programs is thus possible in this
mode.
CP/M-80
i
1
0000
CP/M and run-time workspace
Pascal Library
Turbo interface, editor, and compiler
Error messages. optional
Source text
Symbol table growing downward
CPU stack growing downward
CP/M
HighMem
Figure A-6: Memory map during compilation to a file
167
A.16.1.3 Execution in Memory
A.16.1.3 Execution in Memory
When a program is executed in direct - or memory - mode (i.e. the Memory-
mode on compiler Options menu is selected, see section A.1 ), the memory is
mapped as follows:
I- - - - - -.- - - - - - - - - - - - - - -
t- - - - - -- - - -- - - - - - - - ---
- - -.- - - - - - - - - - - - - - - - ,[ - -
i
- - - - - - -- - - - - - - -- - - - - - -
'- ______ . ___________ __ J __ _
0000
CP/M and run-time workspace
Pascal Library
Turbo interface, editor, and compiler
Error messages, optional
Source text
Object code
Default initial value of HeapPtr
Heap growing upward
Recursion stack growing downward
Default initial value of RecurPtr
CPU stack growing downward
Default initial state of StackPtr
Program variables
CP/M
HighMem
Figure A-7: Memory map during execution in direct mode
When a program is compiled, the end of the object code is known. The heap
pointer HeapPtr is set to this value by default, and the heap grows from here
and upwards in memory towards the recursion stack. The maximum memory
size is B DOS minus one (indicated on the compiler Options menu). Program
variables are stored from this address and downwards. The end of the vari-
ables is the 'top of free memory' which is the initial value of the CPU stack
pointer StackPtr. The CPU stack grows downwards from here towards the
position of the recursion stack pointer RecurPtr, $400 bytes lower than
StackPtr. The recursion stack grows from here downward towards the heap.
168 TURBO Pascal Language Manual
Execution of A Program File A.16.1.4
A.16.1.4 Execution of A Program File
When a program file is executed (either by the Run command with the Com-
file mode on the compiler Options menu selected, by an eXecute command,
or directly from CP/M), the memory is mapped as follows:
- - - - -- - - -- - - - - --
---------------
___ 1 __
____ 1 __ _
------- -------------------
Loader
0000
CP/M and run-time workspace
Pascal Library
Default program start address
Object code
Default initial value of HeapPtr
Heap growing upward
Recursion stack growing downward
Default initial value of RecurPtr
CPU stack growing downward
Default initial state of StackPtr
Program variables
Default end address
Maximum memory size
CP/M
HighMem
Figure A-8: Memory map during execution of a program file
This map resembles the previous, except for the absence of the TURBO inter-
face, editor, and compiler (and possible error messages) and of the source
text. The default program start address (shown on the compiler Options
menu) is the first free byte after the Pascal runtime library. This value may be
manipulated with the Start address command of the compiler Options menu,
e.g. to create space for absolute variables and/or external procedures bet-
ween the library and the code. The maximum memory size is BOOS minus
one, and the default value is determined by the BDOS location on the compu-
ter in use.
CP/M-80 169
A.16.1.4 Execution of A Program File
If programs are to be translated for other systems, care should be taken to
avoid collision with the B The maximum memory may be manipulated
with the End address command of the compiler Options menu. Notice that
the default end address setting is approx. 700 to 1000 bytes lower than max-
imum memory. This is to allow space for the loader which resides just below
BOOS when .COMfiles are Run or eXecuted from the TURBO system. This
loader restores the TU RBO editor, compiler, and possible error messages
when the program finishes and thus returns control to the TURBO system.
A.16.2 The Heap and The Stacks
As indicated by the memory maps in previous sections, three stack-like struc-
tures are maintained during execution of a program: The heap, the CPU stack,
and the recursion stack.
The heap is used to store dynamic variables, and is controlled with the stan-
dard procedures New, Mark, and Release. At the beginning of a program, the
heap pointer HeapPtr is set to the address of the bottom of free memory, i.e
the first free byte after the object code.
The CPU stack is used to store intermediate results during evaluation of ex-
pressions and to transfer parameters to procedures and functions. An active
for statement also uses the CPU stack, and occupies one word. At the begin-
ning of a program, the CPU stack pointer StackPtr is set to the address of the
top of free memory.
The recursion stack is used only by recursive procedures and functions, i.e.
procedures and functions compiled with the A compiler directive passive
On entry to a recursive subprogram it copies its workspace onto the
recursion stack, and on exit the entire workspace is restored to its original
state. The default initial value of RecurPtr at the beginning of a program, is 1 K
($400) bytes below the CPU stack pointer.
Because of this technique, variables local to a subprogram must not be used
as var parameters in recursive calls.
The pre-defined variables:
HeapPtr:
RecurPtr:
StackPtr:
The heap pointer,
The recursion stack pointer, and
The CPU stack pointer
allow the programmer to control the position of the heap and the stacks.
170 TURBO Pascall..£nguage Manual
The Heap and The Stacks A.16.2
The type of these variables is Integer. Notice that HeapPtr and RecurPtr may
be used in the same context as any other Integer variable, whereas StackPtr
may only be used in assignments and expressions.
When these variables are manipulated, always make sure that they point to
addresses within free memory, and that:
HeapPtr < RecurPtr < StackPtr
Failure to adhere to these rules will cause unpredictable, perhaps fatal, re-
sults.
Needless to say, assignments to the heap and stack pointers must never oc-
cur once the stacks or the heap are in use.
On each call to the procedure New and on entering a recursive procedure or
function, the system checks for collision between the heap and the recursion
stack, i.e. checks if HeapPtr is less than RecurPtr. If not. a collision has occur-
red, which results in an execution error.
Note that no checks are made at any time to insure that the CPU stack does
not overflow into the bottom of the recursion stack. For this to happen, a re-
cursive subroutine must call itself some 300-400 times, which must be con-
sidered a rare situation. If, however, a program requires such nesting, the fol-
lowing statement executed at the beginning of the program block will move
the recursion stack pointer downwards to create a larger CPU stack:
RecurPtr := StackPtr -2 *MaXDepth -512;
where MaxDepth is the maximum required depth of calls to the recursive
subprogram(s). The extra approx. 512 bytes are needed as a margin to make
room for parameter transfers and intermediate results during the evaluation of
expressions.
CP/M-80 171
A.16.2 The Heap and The Stacks
Notes:
172 TURBO Pascal Language Manual
MS-DOS/PC-DOS and CP/M-86 B
B. MS-DOS/PC-DOS and CP/M-a6
This appendix describes features of TU RBO pascal specific to the various 16-
bit implementations. The appendix has three sub-sections:
Common features which deals with information common to the MS-
DOS/PC-DOS and the CP/M -86 implementations.
The MS-DOS/PC-DOS implementation which deals with information
specific to the MS-DOS implementation.
The CP/M -86 implementation which deals with information specific to the
CP/M-86 implementation.
B.1 Common features
This section presents two kinds of information:
1) Things you must know to make efficient use of TURBO Pascal. These are
described in section B.1.1 .
2) The remaining sections describe things which are only of interest to expe-
rienced programmers, e.g. calling machine language routines, technical
aspects of the compiler, etc.
8.1.1 Compiler Options
The 0 command selects the following menu from which you may view and
change some default values of the compiler. It also provides a helpful function
to find runtime errors in programs compiled into object code files.
compile -> ~ m o r y
Com- file
cHn- file
Find run-time error Quit
Figure B-1: Options Menu
MS-DOS/PC-DOS and CP/M-86 173
B.l.l Compiler Options
The only difference between the two implementations is that then command
Com-file is called Cmd-file in the CP/M-86 implementation.
B.l.l.l Memory / Com file / cHn -file
The three commands M, C, and H select the compiler mode, i.e. where to put
the code which results from the compilation. Memory is the default mode.
When active, code is produced in memory and resides there ready to be acti-
vated by a Run command.
Com-file is selected by pressing C. The arrow moves to point to this line. The
compiler writes code to a file with the same name as the Work file (or Main
file, if specified) and the file type .COM (in CP/M-86 the file type is .CMD).
This file contains the program code and Pascal runtime library, and may be
activated by typing its name at the console.
cH ain-file is selected by pressing H. The arrow moves to point to this line.
The compiler writes code to a file with the same name as the Work file (or
Main file, if specified) and the file type .CHN. This file contains the program
code but no Pascal library and must be activated from another TURBO Pascal
program with the Chain procedure (see section B.1.9 ).
When the Com or cH n mode is selected, four additional lines will appear on
the screen:
mi ni mum cOde segment size: XXXX paragraphs (max.
yyyy)
minimum Data segment size: XXXX paragraphs (max.
yyyy)
mInimum free dynamic memory: XXXX paragraphs
mAximum free dynamic memory: XXXX paragraphs
Figure B-2: Memory Usage Menu
The use of these commands are described in the following sections.
174 TURBO Pascal Language Manual
Minimum Code Segment Size 8.1.1.2
8.1.1.2 Minimum Code Segment Size
The O-command is used to set the minimum size of the code segment for a
.COM using Chain or Execute. As discussed in section B.1.9 , Chain and Exe-
cute do not change the base addresses of the code, data, and stack seg-
ments, and a 'root' program using Chain or Execute must therefore allocate
segments of sufficient size to accommodate the largest segments in any
Chained or Executed program.
Consequently, when compiling a 'root' program, you must set the value of the
Minimum Code Segment Size to at least the same value as the largest code
segment size of the programs to be chained/executed from that root. The re-
quired values are obtained from the status printout terminating any compila-
tion. The values are in hexadecimal and specify number of paragraphs, a para-
graph being 16 bytes.
8.1.1.3 Minimum Data Segment Size
The D-command is used to set the minimum size of the data segment for a
.COM using Chain or Execute. As discussed above, a 'root' program using
these commands must allocate segments of sufficient size to accommodate
the largest data of any Chained or Executed program.
Consequently, when compiling a 'root' program, you must set the value of the
Minimum Data Segment Size to at least the same value as the largest data
segment size of the programs to be chained/executed from that root. The re-
quired values are obtained from the status printout terminating any compila-
tion. The values are in hexadecimal and specify number of paragraphs, a para-
graph being 16 bytes.
8.1.1.4 Minimum Free Dynamic Memory
This value specifies the minimum memory size required for stack and heap.
The value is in hexadecimal and specifies a number of paragraphs, a para-
graph being 16 bytes.
MS-DOS/PC-DOS and CP/M-86
175
B.1.1.5 Maximum Free Dynamic Memory
B.1.1.5 Maximum Free Dynamic Memory
This value specifies the maximum memory size allocated for stack and heap.
It must be used in programs which operate in a multi-user environment like
Concurrent CP/M -86 to assure that the program does not allocate the entire
free memory. The value is in hexadecimal and specifies a number of para-
graphs, a paragraph being 16 bytes.
B.1.1.6 Find Runtime Error
When you run a program compiled in memory, and a runtime error occurs, the
editor is invoked, and the error is automatically pointed out. This, of course, is
not possible if the program is in a .COM/.CMD file or an .CHN file. Run time
errors then print out the error code and the value of the program counter at
the time of the error, e.g.:
Run-time error 01, PC=1B56
Program aborted
Figure B-3: Run-time Error Message
To find the place in the source text where the error occurred, enter the F com-
mand. When prompted for the address, enter the address given by the error
message:
En t e r PC;---1OO.Q
Figure B -4: Find Run-time Error
The place in the source text is now found and pointed out exactly as if the er-
ror had occurred while running the program in memory.
176 TURBO Pascal Language Manual
Standard Identifiers 8.1.2
8.1.2 Standard Identifiers
The following standard identifiers are unique to the 16-bit implementation:
CSeg
DSeg
Intr
MemW
8.1.3 Absolute Variables
Ofs
PortW
Seg
SSeg
Variables may be declared to reside at specific memory addresses, and are
then called absolute. This is done by adding to the variable declaration the
reserved word absolute followed by two Integer constants specifying a seg-
ment and an offset at which the variable is to be located:
var
Abc: Integer absolute $0000: $08EE;
Def: Integer absolute $0000:$00F0;
The first constant specifies the segment base address, and the second cons-
tant specifies the offset within that segment. The standard identifiers CSeg
and OSeg may be used to place variables at absolute addresses within the
code segment (C5eg) or the data segment (05eg):
Special: a r r ~ [ l .. CodeSize] absolute CSeg:$05F3;
Absolute may also be used to declare a variable "on top" of another variab-
le, i.e. that a variable should start at the same address as another variable.
When absolute is followed by the variable (or parameter) identifier, the new
variable will start at the address of that variable (or parameter).
Example:
var
St r: string[ 32];
StrLen: Byte absolute Str;
This declaration specifies that the variable StrLen should start at the same ad-
dress as the variable Str, and as the first byte of a string variable contains the
length of the string, StrLen will contain the length of Str. Notice that an abso-
lute variable declaration may only specify one identifier.
Further details on space allocation for variables are found in section B.1.12 .
MS-DOS/PC-OOS and CP/M-86 177
B.1.4 Absolute Address Functions
B.1.4 Absolute Address Functions
The following functions are provided for obtaining information about program
variable addresses and system pointers.
B.l.4.1 Addr
Syntax: Addr(Name)
Returns the address in memory of the first byte of the variable with the identi-
fier Name. If Name is an array, it may be subscribed, and if Name is a record,
specific fields may be selected. The value returned is a 32 bit pointer consist-
ing of a segment address and an offset.
B.l.4.2 afs
Syntax: Ofs(Name)
Returns the offset in the segment of memory occupied by the first byte of the
variable, procedure or function with the identifier Name. If Name is an array, it
may be subscribed, and if Name is a record, specific fields may be selected.
The value returned is an Integer.
8.1.4.3 Seg
Syntax: Seg(Name)
Returns the address of the segment containing the first byte of the variable,
procedure or function with the identifier Name. If Name is an array, it may be
subscribed, and if Name is a record, specific fields may be selected. The value
returned is an Integer.
8.1.4.4 Cseg
Syntax: Cseg
Returns the base address of the Code segment. The value returned is an Inte-
ger.
178 TURBO Pascal Language Manual
Dseg B.1.4.5
8.1.4.5 Dseg
Syntax: Dseg
Returns the base address of the Data segment. The value returned is an Inte-
ger.
8.1.4.6 Sseg
Syntax: Sseg
Returns the base address of the Stack segment. The value returned is an Inte-
ger.
B.1.5 Predefined Arrays
TURBO Pascal offers four predefined arrays of type Byte, called Mem,
MemW, Port and PortW which are used to access CPU memory and data
ports.
8.1.5.1 Mem Array
The predefined arrays Mem and Mem Ware used to access memory. Each
component of the array Mem is a byte, and each component of the array
Wmem is a word (two bytes, LSB first). The index must be an address speci-
fied as the segment base address and an offset separated by a colon and both
of type Integer.
The following statement assigns the value of the byte located in segment
0000 at offset $0081 to the variable Value
Va 1 ue : =Mem[ 0080 : $0081] ;
While the following statement:
Merrm[Seg(Var) :Ofs(Var)] :=Value;
places the value of the Integer variable Value in the memory location occu-
pied by the two first bytes of the variable Var.
MS-DOS/PC-DOS and CP/M-86 179
B.1.5.2 Port Array
8.1.5.2 Port Array
The Port and Port W array are used to access the data ports of the 8086/88
CPU. Each element of the array represents a data port, with the index corre-
sponding to port numbers. As data ports are selected by 16-bit addresses the
index type is Integer. When a value is assigned to a component of Port or
Port W it is output to the port specified. When a component of port is referen-
ced in an expression, its value is input from the port specified. The compo-
nents of the Port array are of type Byte and the components of Port Ware of
type Integer.
Example:
Port[ 56] : = 10;
The use of the port array is restricted to assignment and reference in ex-
pressions only, i.e. components of Port and PortW cannot be used as variab-
le parameters to procedures and functions. Furthermore, operations referring
to the entire port array (reference without index) are not allowed.
B.1.6 With Statements
With statements may be nested to a maximum of 9 levels.
B.1 .7 Pointer Related Items
8.1.7.1 MernA vail
The standard function MemAvail is available to determine the available space
on the heap at any given time. The result is an Integer specifying the number
of of available paragraphs on the heap. (a paragraph is 16 bytes).
8.1.7.2 Pointer Values
In very special circumstances it can be of interest to assign a specific value to
a pointer variable without using another pointer variable or it can be of inte-
rest to obtain the actual value of a pointer variable.
180 TURBO Pascal Language Manual
Assigning a Value to a Pointer 8.1.7.2.1
B.1.7.2.1 Assigning a Value to a Pointer
The standard function Ptr can be used to assign specific values to a pointer
variable. The function returns a 32 bit pointer consisting of a segment address
and an offset.
Example:
POinter: =Pt r(Cseg, $80);
B.1.7.2.2 Obtaining The Value of a Pointer
A pointer value is represented as a 32 bit entity and the standard function Ord
can therefore not be used to obtain its value. Instead the functions ors and
Seg must be used.
The following statement obtains the value of the pointer P {which is a seg-
ment address and an offset}:
SegmentPart : );

B.l.8 External Subprograms
The reserved word external is used to declare external procedures and func-
tions, typically procedures and functions written in machine code.
The reserved word external must be followed by a string constant specifying
the name of a file in which executable machine code for the external proce-
dure or function must reside.
During compilation of a program containing external functions or procedures
the associated files are loaded and placed in the object code. Since it is im-
possible to know beforehand exactly where in the object code the external
code will be placed this code must be relocatable, and no references must be
made to the data segment. Furthermore the external code must save the regi-
sters BP, CS, OS and SS and restore these before executing the RET instruc-
tion.
An external subprogram has no block, i.e. no declaration part and no state-
ment part. Only the subprogram heading is specified, immediately followed by
the reserved word external and a filename specifying where to find the exe-
cutable code for the subprogram.
MS-DOS/PC-DOS and CP/M-86 181
B.l.8 External Subprograms
The type of the filename is .COM in the MS-DOS version and .CMD in the
CP/M-86 version. Only the code segment of a .CMD file is loaded.
Example:
procedure Di skReset; external 'DSKRFSEI";
funct ion IOstatus: boo lean; external 'IOSTAT';
Parameters may be passed to external subprograms, and the syntax is exactly
the same as that of calls to ordinary procedures and functions:
procedure Plot(X,Y: Integer); external 'PlDT';
procedure QuickSort(var List: PartNo); external 'QS';
External subprograms and parameter passing is discussed further in section
B.1.12.3.
8.1.9 Chain and Execute
TURBO Pascal provides two procedures Chain and Execute which allow you
to activate other TURBO programs from a TU RBO program. The syntax of the
procedure calls are:
Chain(Fi Ie)
Execute(File)
where File is a file variable of any type, previously assigned to a disk file with
the standard procedure Assign. If the file exists, it is loaded into memory and
executed.
The Chain procedure is used only to activate special TURBO Pascal .CHN fi-
les, i.e. files compiled with the cH n-file option selected on the Options menu
(see section B.1.1.1 ). Such a file contains only program code; no Pascal li-
brary, it uses the Pascal library already present in memory.
The Execute procedure works exactly as if the program had been activated
from the operating system (with the limitation that parameters can not be
passed from the command line).
182 TURBO Pascal Language Manual
Chain and Execute 8.1.9
Chaining and eXecuting TURBO programs does not alter the memory alloca-
tion state. The base addresses and sizes of the code, data and stack segments
are not changed. It is therefore imperative that the first program which exe-
cutes a Chain statement allocates enough memory for the code, data, and
stack segments to accommodate largest .CHN program. This is done by using
the Options menu to change the minimum code, data and free memory sizes
(see section B.1.1 ).
If the disk file does not exist, an I/O error occurs. This error is treated as de-
scribed in section 14.8. When the I compiler directive is passive ({$I-}), pro-
gram execution continues with the statement following the failed Chain or Ex-
ecute statement, and the IOresult function must be called prior to further I/O.
Data can be transferred from the current program to the chained program eit-
her by shared global variables or by absolute address variables.
To insure overlapping, shared global variables should be declared as the very
first variables in both programs, and they must be listed in the same order in
both declarations. Furthermore, both programs must be compiled to the same
size of code and data segments (see sections B.1.1.2 and B.1.1.3 When these
conditions are satisfied, the variables will be placed at the same address in
memory by both programs, and as TURBO Pascal does not automatically ini-
tialize its variables, they may be shared.
Example:
Program MAIN. COM:
program Ma i n;
var
Txt:
CntPrg:
begin
string[ 80] ;
file;
Write('Enter any text: ,);
As s i gn( CntPrg, , ChrCount . ehn' ) ;
Chain(CntPrg) ;
end.
MS-OOS/PC-OOS and CP/M-86 183
B.1.9
Program CHRCQUNT.CHN:
program ChrCount;
var
Txt: string[ 80] ;
NoOfChar,
NoOfUpc,
I: Integer;
begin
NoOfUpc . - 0;
NoOfChar : = Length(Txt);
for I := 1 to length(Txt) do
Chain and Execute
if Txt[ I] in [ 'A' .. 'Z'] then NoOfUpc . - Succ(NoOfUpc);
Write( 'No of characters in entry: ',NoOfChar);
Writeln( '. No of upper case characters: " NoOlUpc,'. ,);
end.
Note that neither Chain nor Execute can be used in direct mode, i.e. from a
program run with the compiler options switch in position Memory (section
B.1.1.1 ).
B.1.10 In -line Machine Code
TURBO Pascal features the inline statements as a very convenient way of in-
serting machine code instructions directly into the program text. An inline sta-
tement consists of the reserved word inline followed by one or more con-
stants, variable identifiers, or location counter references, separated by slash-
es and enclosed in parentheses.
The constants may be either literal constants or constant identifiers, and they
must be of type Integer. Literals generate one byte of code if within the range
0 .. 255 ($OO .. $FF). otherwise two bytes in the standard byte reversed format.
Constant identifiers always generate two bytes of code.
A variable identifier generates two bytes of code (in byte reversed format)
containing the offset of the variable within its base segment. Global, local and
typed constants occupies different segments as follows:
Global variables resides in the data segment and the offset generated is re-
lative to the OS register.
184 TURBO Pascal Language Manual
In -line Machine Code B.1.10
Local variables reside in the stack segment and the offset generated is rela-
tive to the S P register.
Typed constants reside in the code segment and the offset generated is re-
lative to the CS register.
When an inline statement terminates, the registers SP, SP, DS, and SS must
be restored to their original values before the inline statement.
A location counter reference consists of an asterisk, optionally followed by an
offset consisting of a plus or a minus sign and an Integer constant. An aste-
risk alone generates two bytes of code (in byte reversed format) containing
the current location counter value. If the asterisk is followed by an offset, it is
added or subtracted before coding the address.
The following example of an inline statement generates machine code that
will convert all characters in its string argument to upper case.
procedure UpperCase(var Strg: Str); {Str is type St ring[ 255] }
begin
inline
($04/ $BE/St rg/
{
LES DI,Strg[BP]
}
$26/ $8A/ $0D/
{
MOO CL,E8:[DIJ
}
$FE/$C1/
{
INC CL
}
$FE/$09/
{
L1 : DED CL
}
$74/$13/
{
JZ L2
}
$47/
{
INC DI
}
$26/$88/$3D/$61/
{
CMP E8 : BYTE PI'R [DI J , 'a'}
$72/$F5/
{
JB L1
}
$26/$88/$3D/$7Aj
{
CMP E8 : BYTE PI'R [DI J , ' z' }
$77/$EF/
{
JA L1
}
$26/$88/$2D/$28/
{
SUB ES : BYTE PI'R [DIJ,28H}
$EB/$E9);
{
JMP SHORT Ll
}
{
L2:
}
end;
Inline statements may be freely mixed with other statements throughout the
statement part of a block, and inline statements may use all CPU registers.
Note, however, that the contents of the registers SP, SP, DS, and SS must
be the same on exit as on entry.
MS-DOS/PC-DOS and CP/M-86 185
B.1.11 Interrupt Handling
B.1.11 Interrupt Handling
The TURBO Pascal run time package and the code generated by the compiler
are both fully interruptible. Interrupt service routines must preserve all regi-
sters used.
If required, interrupt service procedures may be written in Pascal. Such proce-
dures must not have parameters, and they must themselves insure that all re-
gisters used are preserved. This is done by placing the following inline state-
ment in the very beginning of the procedure:
in1 ina ($50/ $53/ $51/ $52/ $57/ $56/ $06/ $FB);
and this inline statement at the very end of the procedure:
in1 ine ($07 /$5E/$5F/$5A/$59/ $5B/ $58/ $OF);
The last instruction of the terminating inline statement is an IRET instruction
($CF), which will override the RET instruction generated by the compiler.
An interrupt service procedure should not employ any I/O operations using
the standard procedures and functions of TURBO Pascal, as the BDOS is not
re-entrant. CP/M -86 users should note that B DOS calls should not be per-
formed from interrupt handlers, as these routines are not re-entrant. The pro-
grammer must initialize the interrupt vector used to activate the interrupt ser-
vice routine.
B.1.11.1 Intr procedure
Syntax: Intr( InterruptNo, Result)
This procedure initializes the registers and flags as specified in the parameter
Result which must be of type:
Resul t = record
AX,BX,CX,DX,BP,SI,DI,DS,ES,Flags: Integer;
end;
It then makes the software interrupt given by the parameter interrupt No
which must be an Integer constant. When the interrupt service routine returns
control to your program, Result will contain any values returned from the ser-
vice routine.
186 TURBO Pascal Language Manual
Internal Data Formats 8.1.12
8.1.12 Internal Data Formats
In the following descriptions, the symbol@ denotes the offset of the first byte
occupied by a variable of the given type within its segment. The segment base
address can be determined by using the standard function Seg.
Global and local variables, and typed constants occupy different segments as
follows:
Global variables reside in the data segment and the offset is relative to the
OS register.
Local variables reside in the stack segment and the offset is relative to the
BP register.
Typed constants reside in the code segment and the offset is relative to the
CS register.
All variables are contained within their base segment.
B.1.12.1 Basic Data Types
The basic data types may be grouped into structures (arrays, records, and disk
files), but this structuring will not affect their internal formats.
8.1.12.1.1 Scalars
The following scalars are all stored in a single byte: Integer subranges with
both bounds in the range 0 .. 255, booleans, chars, and declared scalars with
less than 256 possible values. This byte contains the ordinal value of the va-
riable.
The following scalars are all stored in two bytes: Integers, Integer subranges
with one or both bounds not within the range 0 .. 255, and declared scalars
with more than 256 possible values. These bytes contain a 2's complement
16-bit value with the least significant byte stored first.
MS-OOS/PC-OOS and CP/M-86 187
B.1.12.1.2 Reals
8.1.12.1.2 Reals
Reals occupy 6 bytes, giving a floating point value with a 40'-bit mantissa and
an 8-bit 2's exponent. The exponent is stored in the first byte and the man-
tissa in the next five bytes which the least significant byte first:
@ Exponent
@ + 1 LSB of mantissa
@ +5 MSB of mantissa
The exponent uses binary format with an offset of$80. Hence, an exponent of
$84 indicates that the value of the mantissa is to be multiplied by 2 ~ ($84-
$80) = 2 ~ 4 = 16. If the exponent is zero, the floating point value is conside-
red to be zero.
The value of the mantissa is obtained by dividing the 40-bit unsigned integer
by Z' 40. The mantissa is always normalized, i.e. the most significant bit (bit 7
of the fifth byte) should be interpreted as a 1. The sign of the mantissa is sto-
red in this bit, however, a 1 indicating that the number is negative, and a 0 in-
dicating that the number is positive.
8.1.12.1.3 Strings
A string occupies as many bytes as its maximum length plus one. The first
byte contains the current length of the string. The following bytes contains
the string with the first character stored at the lowest address. In the table
shown below, L denotes the current length of the string, and Max denotes the
maximum length:
188
@
@ +1
@+2
@ +L
@ +L+1
@+Max
Current length (L)
First character
Second character
Last character
Unused
Unused
TURBO Pascal Language Manual
Sets B.1.12.1.4
8.1.12.1.4 Sets
An element in a Set occupies one bit, and as the maximum number of ele-
ments in a set is 256, a set variable will never occupy more than 32 bytes
(256/8).
If a set contains less than 256 elements, some of the bits are bound to be
zero at all times and need therefore not be stored. In terms of memory effi-
ciency, the best way to store a set variable of a given type would then be to
"cut off" all insignificant bits, and rotate the remaining bits so that the first
element of the set would occupy the first bit of the first byte. Such rotate ope-
rations, however, are quite slow, and TURBO therefore employs a compro-
mise: Only bytes which are statically zero (i.e. bytes of which no bits are used)
are not stored. This method of compression is very fast and in most cases as
memory efficient as the rotation method.
The number of bytes occupied by a set variable is calculated as (Max div 8) -
(Min div 8) + 1, where Max and Min are the upper and lower bounds of the
base type of that set. The memory address of a specific element E is:
MemAddress = @ + (E div 8) - (Min div 8)
and the bit address within the byte at MemAddress is:
BitAddress = E mod 8
where E denotes the ordinal value of the element.
8.1.12.1.5 Pointers
A pointer consists of four bytes containing a segment base address and an
offset. The two least significant bytes contains the offset and the two most
significant bytes the base address. Both are stored in memory using byte re-
versed format, i.e. the least significant byte is stored first. The value nil corre-
sponds to two zero words.
8.1.12.2 Data Structures
Data structures are built from the basic data types using various structuring
methods. Three different structuring methods exist: Arrays, records, and disk
files. The structuring of data does not in any way affect the internal formats of
the basic data types.
MS-DOS/PC-DOS and CP/M-86 189
B.1.12.2.1 Arrays
8.1.12.2.1 Arrays
The components with the lowest index values are stored eft the lowest me-
mory address. A multi-dimensional array is stored with the rightmost dimen-
sion increasing first, e.g. given the array
Board: a r r ~ [ l .. 8,1 .. 8] of Square
you have the following memory layout of its components:
lowest address: Boardf1,11
Boardf1,21
Boardf1,81
Boardf2,11
Boardf2,21
Highest address:Boardf8,81
8.1.12.2.2 Records
The first field of a record is stored at the lowest memory address. If the record
contains no variant parts, the length is given by the sum of the lengths of the
individual fields. If a record contains a variant, the total number of bytes occu-
pied by the record is given by the length of the fixed part plus the length of
largest of its variant parts. Each variant starts at the same memory address.
8.1.12.2.3 Disk Files
Disk files are different from other data structures in that data is not stored in
internal memory but in a file on an external device. A disk file is controlled th-
rough a file interface block (FIB) as described in sections B.3.4 and B.2.4 . In
general there are two different types of disk files: random access files and text
files.
190 TURBO Pascal Language Manual
Text Files 8.1.12.2.4
B.1.12.2.4 Text Files
The basic components of a text file are characters, but a text file is further-
more divided into lines. Each line consists of any number of characters ended
by a CR/LF sequence (ASCII $00/ $OA). The file is terminated by a Ctrl-Z
(ASCII $1B).
8.1.12.3 Parameters
Parameters are transferred to procedures and functions via the stack which is
addressed through SS:SP.
On entry to an external subroutine, the top of the stack always contains the
return address within the code segment (a word). The parameters, if any, are
located below the return address, i.e. at higher addresses on the stack.
If an external function has the following subprogram header:
function Magic(var R: Real; S: string5): Integer;
then the stack upon entry to Magic would have the following contents:
< Function result >
< Segment base address of R >
< Offset address of R >
< Mantissa of R next 5 bytes >
< First character of S >
< Last character of S >
< Length of S >
< Return address > SP
An external subroutine should save the Base Page register (BP) and then copy
the Stack Pointer SP into the Base Page register in order to be able to refer to
parameters. Furthermore the subroutine should reserve space on the stack for
local workarea. This can be obtained by the following instructions:
PUSH BP
MOV BP,SP
SUB SP, WORKARFA
MS-OOS/PC-OOS and CP/M-86 191
B.1.12.3 Parameters
The last instruction will have the effect of adding the following to the stack:
< Return address > BP
< TbB saved BP register >
< First byte of local ~ o r k a r e a >
< Last byte of local work area> SP
Parameters are accessed via the BP register.
The following instruction will load length of the string into the AL register:
MOV AL, [BP-l]
Before executing a RET instruction the subprogram must reset the Stack
Pointer and Base Page register to their original values. When executing the
RET the parameters may be removed by giving RET a parameter specifying
how many bytes to remove. The following instructions should therefore be
used when exiting from a subprogram:
MOV SP,BP
FQP BP
~ NoOfBytesTtiRemove
8.1.12.3.1 Variable Parameters
With a variable (var) parameter, two words are transferred on the stack giving
the base address and offset of the first byte occupied by the actual para-
meter.
8.1.12.3.2 Value Parameters
With value parameters, the data transferred on the stack depends upon the
type of the parameter as described in the following sections.
192 TURBO Pascal Language Manual
Scalars 8.1.12.3.2.1
B.1.12.3.2.1 Scalars
Integers, Booleans, Chars and declared scalars (Le. all scalars except Reals)
are transferred on the stack as a word. If the variable occupies only one byte
when it is stored, the most significant byte of the parameter is zero.
B.1.12.3.2.2 Reals
A real is transferred on the stack using six bytes.
B.1.12.3.2.3 Strings
When a string is at the top of the stack, the topmost byte contains the length
of the string followed by the characters of the string.
B.1 .12.3.2.4 Sets
A set always occupies 32 bytes on the stack (set compression only applies to
the loading and storing of sets).
B.1.12.3.2.5 Pointers
A pointer value is transferred on the stack as two words containing the base
address and offset of a dynamic variable. The value NIL corresponds to two
zero words.
B .1.12.3.2.6 Arrays and.Records
Even when used as value parameters, Array and Record parameters are not
actually transferred on the stack. Instead, two words containing the base ad-
dress and offset of the first byte of the parameter are transferred. It is then the
responsibility of the subroutine to use this information to make a local copy of
the variable.
MS-DOS/PC-DOS and CP/M-86 193
B.1 .1 2.4 Function Results
8.1.12.4 Function Results
User written external functions must remove all parameters and the function
result from the stack when they return.
User written external functions must return their results exactly as specified
in the following:
Values of scalar types, except Reals, must be returned in the AX register. If
the result is only one byte then AH should be set to zero. Boolean functions
must return the function value by setting the Z flag (Z = False, NZ = True).
Reals must be returned on the stack with the exponent at the lowest address.
This is done by not removing the function result variable when returning.
Sets must be returned on the top of the stack according to the format descri-
bed in section B.1.12.3.2.3. On exit SP must point at the byte containing the
string length.
Pointer values must be returned in the DX:AX.
8.1.12.5 The Heap and The Stacks
During execution of TURBO Pascal program the following segments are allo-
cated for the progam:
a Code Segment,
a Data Segment, and
a Stack Segment
Two stack-like structures are maintained during execution of a program: the
heap and the stack.
The heap is used to store dynamic variables, and is controlled with the stan-
dard procedures New, Mark, and Release. At the beginning of a program, the
heap pointer HeapPtr is set to low memory in the stack segment and the heap
grows upwards towards the stack. The pre-defined variable HeapPtr contains
the value of the heap pointer and allows the programmer to control the po-
sition of the heap.
194 TURBO Pascal Language Manual
The Heap and The Stacks 8.1.12.5
The stack is used to store local variables, intermediate results during evalua-
tion of expressions and to transfer parameters to procedures and functions. At
the beginning of a program, the stack pointer is set to the address of the top
of the stack segment.
On each call to the procedure New and on entering a procedure or function,
the system checks for collision between the heap and the recursion stack. If a
collision has occurred, an execution error results, unless the K compiler direc-
tive is passive ({$K-}).
MS-DOS/PC-DOS and CP/M-86 195
B.2 The MS-DOS / PC-DOS Implementations
8.2 The MS-DOS / PC-DOS Implementations
This section covers items peculiar to the MS-DOS and PC-DOS versions of
TURBO Pascal. For the sake of clarity and ease, these two operating systems
will simply be referred to as DOS in the following.
8.2.1 Standard Identifiers
The following standard identifiers are unique to the DOS implementations:
LongFilePos LongSeek
LongFileSize MsDos
8.2.2 Function Calls
For the purpose of making DOS system calls, TURBO Pascal introduces a
procedure MsDos, which has a record as parameter.
Details on DOS system calls and BIOS routines are found in the MS-DOS
Operating System Manual published by MicroSoft.
The parameter to MsDos must be of the type:
record
AX,BX,CX,DX,BP,SI,DI,DS,ES,Flags: Integer;
end;
Before TURBO makes the DOS system call the registers AX, BX, CX, OX, BP,
SI, 01, OS, and ES are loaded with the values specified in the record para-
meter. When DOS has finished operation the MSdos procedure will restore
the registers to the record thus making any results from DOS available.
8.2.3 User Written I/O Drivers
For some applications it is practical for a programmer to define his own input
and output drivers, i.e. routines which perform input and output of characters
to and from an external device. The following drivers are part of the TURBO
environment, and used by the standard I/O drivers (although they are not
available as standard procedures or functions):
196 TURBO Pascal Language Manual
User Written I/O Drivers
function
function
procedure
procedure
procedure
function
procedure
function
CanSt: boolean; { 11 }
Canln: Char; { 8 }
CanOut(Ch: Char); {2 }
LstOut(Ch: Char); { 5 }
AuxOut(Ch: Char); {4}
Auxin: Char; { 3 }
UsrOut(Ch: Char); {2 }
Usrln: Char; { 8 }
8.2.3
The CanSt routine is called by the function KeyPressed, the Canln and Can-
Out routines are used by the CON:, TRM:, and KB D: devices, the LstOut rou-
tine is used by the LST: device, the AuxOut and Auxin routines are used by
the AUX: device, and the UsrOut and Usrln routines are used by the USR: de-
vice.
By default, these drivers are assigned to the DOS system calls as showed in
curly brackets in the above listing of drivers.
This, however, may be changed by the programmer by assigning the address
of a self-defined driver procedure or a driver function to one of the following
standard variables:
Variable
CanStPtr
CanlnPtr
CanOutPtr
LstOutPtr
AuxOutPtr
AuxlnPtr
UsrOutPtr
UsrlnPtr
Contains the address of the
CanSt function
Canln function
Can Out procedure
LstOut procedure
AuxOut procedure
Auxin function
UsrOut procedure
Usrln function
A user defined driver procedure or driver function must match the definitions
given above, i.e. a CanSt driver must be a boolean function, a Canln driver
must be a char function, etc.
MS-DOS/PC-DOS and CP/M-86 197
B.2.4 File Interface Blocks
B.2.4 file Interface Blocks
Each file variable in a program has an associated file interface block (FIB). A
FIB occupies 176 bytes of memory and is for files of type text divided into two
sections: The control section (the first 48 bytes), and the sector buffer (the
last 128 bytes). The control section contains various information on the disk
file or device currently assigned to the file. The sector buffer is used to buffer
input and output from and to the disk file. Random access file variables and
untyped file variables does not have buffer section and therefore occupies
only 48 bytes.
The table below shows the format of a FIB:
@ Flags byte
@ +1 File type
@+2 iCharacter buffer
@+3 Sector buffer pointer
@+4 Number of records (LSB)
@+7 Number of records (MSB)
@+8 Unused (reserved)
@ +10 Unused (reserved)
@ +11 First byte of DOS FCB
@+25 Record length in bytes (LSB)
@+26 Record length in bytes (MSB)
@+44 Current record number (LSB)
@+47 Current record number (MSB).
(Last byte of FCB)
@ +48 First byte of sector buffer
@ +175 Last byte of sector buffer
The flags byte at@ contains two one-bit flags which indicate the current sta-
tus of the file:
bit 0
bit 1
Input flag. High if input is allowed.
Output flag. High if output is allowed.
The file type field at@ + 1 specifies the type of device currently assigned to the
file variable. The following values can occur:
198 TURBO Pascal Language Manual
File Interface Blocks
o
1
2
3
4
5
6
The console device (CON:)
The terminal device (TRM:)
The keyboard device (KB D:)
The list device (LST:)
The auxiliary device (AUX:)
The user device (USR:)
A disk file
B.2.4
When a file is assigned to a logical device, only the first three bytes of the FIB
are of significance.
The sector buffer pointer at @ +3 contains an offset from the first byte of the
sector buffer.
The 'number of records' field starting at@ +4 is a 32-bit number. All DOS file
I/O is performed through system functions 39 and 40 {random block read and
random block write), and the record length field in the FCB is always set to 1.
The sector buffer starting at @ +48 is included in file variables of type Text
only. Random access file variables and untyped file variables occupy only 48
bytes, and data is always transferred directly to or from the variable to be read
or written, leaving all blocking and deblocking to DOS.
8.2.5 Random Access Rles
A random access file consists of a sequence of records, all of the same length
and same internal format. To optimize file storage capacity, the records of a
file are totally contiguous.
TU RBO saves no information about the record length. The programmer must
therefore see to it that a random access file is accessed with the correct re-
cord length.
The size returned by the standard function Filesize is obtained form the DOS
directory.
MS-DOS/PC-DOS and CP/M-86 199
B.2.6 Operations on Files
B.2.6 Operations on Files
B.2.6.1 Extended File Size
The following three additional file routines exist to accommodate the ex-
tended range of records in DOS. These are:
LongFileSize function,
LongFilePosition function, and
LongSeek procedure
They correspond to their Integer equivalents FileSize, File Position, and Posi-
tion but operate with Rea Is . The functions thus return results of type Real, and
the second parameter of the LongSeek procedure must be an expression of
type Real.
B.2.6.2 File of Byte
In the CP/M implementations, access to non-TURBO files (except text files)
must be done through untyped files because the two first bytes of typed
TURBO files always contain the number of components in the file. This is not
the case in the DOS versions, however, and a non-TURBO file may therefore
be declared as a file of byte and accessed randomly with Seek, Read, and
Write.
B.2.6.3 Flush Procedure
The Flush procedure has no effect in DOS, as DOS file variables do not emp-
loy a sector buffer.
200 TURBO Pascal Language Manual
The CP/M-86 Implementation B.3
B.3 The CP/M -86 Implementation
8.3.1 Standard Identifiers
The standard identifier Bdos is unique to the CP/M-86 implementation
8.3.2 Function Calls
For the purpose of calling the CP/M-86 BDOS, TURBO Pascal introduces a
procedure Bdos, which has a record as parameter.
Details on BDOS and BIOS routines are found in the CP/M-86 Operating Sy-
stem Manual published by Digital Research.
The parameter to Bdos must be of the type:
record
AX,BX,CX,DX,BP,SI,DI,DS,ES,Flags: Integer;
end;
Before TURBO calls the BDOS the registers AX, BX, CX, DX, BP, SI, DI, DS,
and ES are loaded with the values specified in the record parameter. When
the BDOS has finished operation the Bdos procedure will restore the regis-
ters to the record thus making any results from the B DOS available.
8.3.3 User Written I/O Drivers
For some applications it is practical for a programmer to define his own input
and output drivers, i.e. routines which perform input and output of characters
to and from an external device. The following drivers are part of the TURBO
environment, and used by the standard I/O drivers (although they are not
available as standard procedures or functions):
function
function
procedure
procedure
procedure
function
procedure
function
ConSt: boolean; {6}
Conln: Char; { 6 }
ConOut(Ch: Char); { 6 }
LstOut(Ch: Char); { 5 }
AuxOut(Ch: Char); {4}
AuxIn: Char; { 3 }
UsrOut(Ch: Char); { 6 }
Usrln: Char; { 6 }
MS-DOS/PC-DOS and CP/M-86 201
B.3.3 User Written I/O Drivers
The ConSt routine is called by the function KeyPressed, the Conln and Con-
Out routines are used by the CON:, TRM:, and KBD: devices, the LstOut rou-
tine is used by the LST: device, the AuxOut and AuxIn routines are used by
the AUX: device, and the UsrOut and Usrln routines are used by the USR: de-
vice.
By default, these drivers are assigned to the BOOS functions as showed in
curly brackets in the above listing of drivers.
This, however, may be changed by the programmer by assigning the address
of a self-defined driver procedure or a driver function to one of the following
standard variables:
Variable
ConStPtr
ConlnPtr
ConOutPtr
LstOutPtr
AuxOutPtr
AuxlnPtr
UsrOutPtr
UsrlnPtr
Contains the address of the
ConSt function
Conln function
Con Out procedure
LstOut procedure
AuxOut procedure
AuxIn function
UsrOut procedure
Usrln function
A user defined driver procedure or driver function must match the definitions
given above, i.e. a ConSt driver must be a boolean function, a Conln driver
must be a char function, etc.
B.3.4 Rle Interface Blocks
Each file variable in a program has an associated file interface block (FIB). A
FIB occupies 176 bytes of memory and is divided into two sections: The con-
trol section (the first 48 bytes), and the sector buffer (the last 128 bytes). The
control section contains various information on the disk file or device cur-
rently assigned to the file. The sector buffer is used to buffer input and output
from and to the disk file.
202 TURBO Pascal Language Manual
File Interface Blocks B.3.4
The table below shows the format of a FI B:
@
@ +1
@+2
@+3
@+4
@+5
@+6
@+7
@+8
@+9
@ +10
@ +11
@ +12
@+47
@+48
@ +175
Flags byte
File type
Character buffer
Sector buffer pointer
Number of records (LSB)
Number of records (MSB)
Record length in bytes (LSB)
Record length in bytes (MSB)
Current record number (LSB)
Current record number (MSB)
Unused (reserved)
Unused (reserved)
First byte of CP/M FCB
Last byte of CP/M FCB
First byte of sector buffer
Last byte of sector buffer
The flags byte at@ contains four one bit flags which indicate the current sta-
tus of the file:
bit 0
bit 1
bit 2
bit 3
Input flag. High if input is allowed.
Output flag. High if output is allowed.
Write semaphore. High if data has been written to
the sector buffer.
Read semaphore. High if the contents of the sector
buffer is undefined.
The file type field at@ + 1 specifies the type of device currently assigned to the
file variable. The following values can occur:
o
1
2
3
4
5
6
The console device (CON:)
The terminal device (TRM:)
The keyboard device (KBD:)
The list device (LST:)
The auxiliary device (AUX:)
The user device (USR:)
A disk file
MS-DOS/PC-DOS and CP/M-86 203
B.3.4 File Interface Blocks
The sector buffer pointer at @ +3 contains an offset from the first byte of the
sector buffer. The following three fields are used only by random access files
(defined files) and untyped files. Each field consists of two bytes in byte rever-
sed format. Bytes@ + 10 and @ + 11 are currently unused, but reserved for fu-
ture expansion. Bytes@ +12 through@ +47 contain a CP/M file control block
(FCB). The last block of the FIB is the sector buffer used for buffering input
and output from and to disk files.
When a file is assigned to a logical device, only the first three bytes of the FIB
are of significance.
The FIB format described above applies to all defined files and textfiles. The
FIB of an untyped file has no sector buffer, as data is transferred directly bet-
ween a variable and the disk file. Thus, the length of the FIB of an untyped file
is only 48 bytes.
8.3.5 Random Access Rles
A random access file consists of a sequence of records, all of the same length
and same internal format. To optimize file storage capacity, the records of a
file are totally contiguous. The first four bytes of the first sector of a file con-
tains the number of records in the file and the length of each record in bytes.
The first record of the file is stored starting at the fourth byte.
204
sector 0, byte 0:
sector 0, byte 1 :
sector 0, byte 2:
sector 0, byte 3:
Number of records (LSB)
Number of records (MSB)
Record length (LSB)
Record length (MSB)
TURBO Pascal Language Manual
SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS C
C. SUMMARY OF STANDARD PROCEDURES AND
FUNCTIONS
This appendix lists all standard procedures and functions available in TURBO
Pascal and describes their syntax, thewir parameters, and their types. The fol-
lowing symbols are used to denote elements of various types:
type
string
file
scalar
pointer
any type
any string type
any file type
any scalar type
any pointer type
Where parameter type specification is not present, it means that the pro-
cedure or function accepts variable parameters of any type.
C.1 Input/Output Procedures and Functions
The following procedures use a non-standard syntax in their parameter lists:
procedure
Read (var F: file of type; var v: type);
Read (var F: text; var I: Integer);
Read (var F: text; var R: Real);
Read (var F: text; var C: Char);
Read (var F: text; var S:string);
Readln (var F: text);
Write (var F: file of type; var v: type);
Write (var F: text; I: Integer);
Write (var F: text; R: Real);
Write (var F: text; B: Boolean);
Write (var F: text; C: Char);
Write (var F: text; S:string);
Writeln (var F: text);
SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS 205
C.2 Arithmetic Functions
C.2 Arithmetic Functions
function
Abs (/: Integer): Integer;
Abs (R: Real): Real;
ArcTan (R: Real): Real;
Cos (R: Real): Real;
Exp (R: Real): Real;
Frac (R: Real): Real;
Int (R: Real): Real;
Ln (R: Real): Real;
Sin (R: Real): Real;
Sqr (/: Integer): Integer;
Sqr (R: Real): Real;
Sqrt (R: Real): Real;
C.3 Scalar Functions
function
Odd (/: Integer): Boolean;
Pred (X: scalar): scalar;
Succ (X: scalar): scalar;
C.4 Transfer Functions
function
206
Chr (I: Integer): Char;
Ord (X: scalar): Integer;
Round (R: Real): Integer;
Trunc (R: Real): Integer;
TURBO Pascal Language Manual
String Procedures and Functions
C.s String Procedures and Functions
The Str procedure uses a non-standard syntax for its numeric parameter.
procedure
Delete (var S:string; Pos, Len: Integer);
Insert (S:string; var D: string; Pos: Integer);
Str (/: Integer; var S:string);
Str (R: Real; var S:string);
Val (S:string; var R: Real; var p: Integer);
Val (S:string; var/, P: Integer);
function
Concat (S1 ,S2, ... ,Sn: string): string;
Copy (S: string; Pos, Len: Integer): string;
Length (S:string): Integer;
Pas (Pattern, Source: string): Integer;
C.6 File handling routines
procedure
Assign (var F: file; name: string);
BlockRead (var F: file; var Dest: Type; Num: Integer);
BlockWrite (var F: file; var Dest: Type; Num: Integer);
Chain (var F: file);
Close (var F:file);
Erase (var F: file);
Execute (var F: file);
Rename (var F: file; Name: string);
Reset (var F:file);
Rewrite (var F:file);
Seek (var F: file of type; Pos: Integer);
function
Eof (var F:file): Boolean;
Eoln (var F: Text): Boolean;
FilePos (var F: file of type): Integer;
FilePos (var F: file): Integer;
FileSize (var F: file of type): Integer;
FileSize (var F: file): Integer;
Seek (var F: file; paS: Integer);
C.5
SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS 207
C.7 Heap Control Procedures and Functions
C.7 Heap Control Procedures and Functions
procedure
GetMem (var P: pointer; I: Integer);
Mark (var P:pointer);
New (var P:pointer);
Release (var P:pointer);
function
MemAvail : Integer;
Ord (P:pointer): Integer;
Ptr (/: Integer):pointer;
C.s Screen Related Procedures
procedure
CrtExit;
Crtlnit;
ClrEol;
ClrScr;
DelLine;
GotoXY (X, Y: Integer);
InsLine;
LowVideo;
NormVideo;
C.9 Miscellaneous Procedures and Functions
procedure
208
Bdos (func,param: Integer);
Bios (func,param: Integer);
Delay (mS: Integer);
FiIIChar (var dest; length: Integer; data: Char);
FillChar (var dest; length: Integer; data: byte);
Halt;
Move (var source,dest; length: Integer);
Randomize;
TURBO Pascal Language Manual
Miscellaneous Procedures and Functions
function
Addr (var variable): Integer;
Addr (function identifier»): Integer;
Addr (procedure identifier»): Integer;
Bdos (Func, Param: Integer): Byte;
B dosH L (Func, Param: Integer): Integer;
Bios (Func, Param: Integer): byte;
B iosH L (Func, Param: Integer): Integer;
Hi (/: Integer): Integer;
IOresult : Boolean;
KeyPressed : Boolean;
La (/: Integer): Integer;
Random (Range: Integer): Integer;
Random: Real;
SizeOf (var variable): Integer;
SizeOf (type identifier»): Integer;
Swap (/: Integer): Integer;
UpCase (Ch: Char): Char;
C.9
SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS 209
G.9 Miscellaneous Procedures and Functions
Notes:
210 TURBO Pascal Language Manual
SUMMARY OF OPERATORS D
D. SUMMARY OF OPIERATORS
The following table summrizes all operators of TURBO Pascal. T.he operators
are grouped in order of decending precedence. Where Type of operand is in-
dicated as Integer, Real, the result is as follows:
Operands
I nteger, Integer
Real, Real
Real, Integer
Result
Integer
Real
Real
Operator Operation
+ unary
- unary
not
*
/
div
mod.
and
shl
shr
+
or
xor
sign ident i ty
sign inversion
negation
mul t ipl icat ion
set intersection
division
Integer division
modulus
arithmeticl and
logical and
shift left
shift right
addition
concatenation
set union
subtraction
set difference
arithmeticl or
logical or
ari thmet ic 1 xor
logical xor
SUMMARY OF OPERATORS
TYPe of operand(s)
Integer, Real
Integer, Real
Integer, Boolean
Integer, Real
any set type
Integer, Real
Integer
Integer
Integer
Boolean
Integer
Integer
Integer, Real
string
any set type
Integer, Real
any set type
Integer
Boolean
Integer
Boolean
TYPe of resul t
as operand
as operand
as operand
Integer, Real
as operand
Real
Integer
Integer
Integer
Boolean
Integer
Integer
Integer, Real
string
as operand
Integer, Real
as operand
Integer
Boolean
Integer
Boolean
211
D
<>
>
<
in
equal i ty
equal i ty
equal i ty
equal i ty
inequal i ty
inequal i ty
inequal i ty
inequal i ty
greater or equal
greater or equal
set inc lus ion
less or equal
less or equal
set inc lus ion
greater than
greater than
less than
less than
set membership
SUMMARY OF OPERATORS
any scalar type
string
any set type
any pOinter type
any scalar type
string
any set type
any pOinter type
any scalar type
st ring
any set type
any scalar type
string
any set type
any scalar type
string
any scalar type
st ring
see below
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boo lean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
Boolean
The first operand of the in operator may be of any scalar type, and the second
operand must be a set of that type.
212 TURBO Pascal Language Manual
SUMMARY OF COMPILER DIRECTIVES E
E. SUMMARY OF COMPILER DIRECTIVES
A number of features of the TURBO Pascal compiler are controlled through
compiler directives. A compiler directive is introduced as a comment with a
special syntax which means that whenever a comment is allowed in a pro-
gram, a compiler directive is also allowed.
A compiler directive consists of an opening bracket immediately followed by a
dollar-sign immediately followed by one compiler directive letter or a list of
compiler directive letters separated by commas, ultimately terminated by a
closing bracket.
Examples:
{$I - }
{$I INCLUDE. FIL}
{$B-,R+,V-}
( *$X-*)
Notice that no spaces are allowed before or after the dollar-sign. A + sign af-
ter a directive indicates that the associated compiler feature is enabled (ac-
tive), and a minus sign indicates that is disabled (passive).
IMPORTANT NOTICE
All compiler directives have default values. These have been chosen
to optimize execution speed and minimize code size. This means that
e.g. code generation for recursive procedures (CP/M-80 only) and in-
dex checking has been disabled. Check below to make sure that your
programs include the required compiler directive settings!
SUMMARY OF COMPILER DIRECTIVES 213
E.1 Common Compiler Directives
E.1 Common Compiler Directives
E.1.1 B-1 /0 Mode Selection
Default: B+
The B directive controls input/output mode selection. When active, { $B+},
the CON: device is assigned to the standard files Input and Output, i.e. the de-
fault input/output channel. When passive, { $B-I, the TRm: device is used.
This directive is global to an entire program block and cannot be re-
defined throughout the program. See sections 14.5.3 and 14.6.1 for further
details.
E.1.2 C - Control Sand C
Default: c+
The C directive controls control character interpretation during console I/O.
When active, {$C+J, a Ctrl-C entered in response to a Read or Readln state-
ment will interrupt program execution, and a Ctrl-S will toggle screen output
off and on. When passive, {$C-J, control characters are not interpreted. The
active state slows screen output somewhat, so if screen output speed is im-
perative, you should switch off this directive. This directive is global to an
entire program block and cannot be re-defined throughout the program.
E.1.3 I - I/O Error Handling
Default: 1+
The I directive controls I/O error handling. When active, {$I+J, all I/O opera-
tions are checked for errors. When passive, {$I-J, it is the responsibility of the
programmer to check I/O errors through the standard function IOresult. See
section 14.8 for further details.
E.1.4 I - Include Rles
The I directive succeeded by a file name instructs the compiler to include the
file with the specified name in the compilation. Include files are discussed in
detail in chapter 1 7 .
214 TURBO Pascal Language Manual
R - Index Range Check E.1.5
E.l.5 R - Index Range Check
Default: R-
The R directive controls run-time index checks. When active, {$R+}. all array
indexing operations are checked to be within the defined bounds, and all as-
signments to scalar and subrage variables are checked to be within range.
When passive, {$R-J. no checks are performed, and index errors may well
cause a program to go haywire. It is a good idea to activate this directive
while developing a program. Once debugged, execution will be speeded up by
setting it passive (the default state). For forther discussion, see sections 8.4
and 10.1 .
E.l.6 V - Var-parameter Type Checking
Default:V+
The V compiler directive controls type checking on strings passed as var-
parameters. When active, { $V+}, strict type checking is performed, i.e. the
lengths of actual and formal parameters must match. When passive, {$V -},
the compiler allows passing of actual parameters which do not match the
length of the formal parameter. See sections A.3 and B.1.3 for further details.
E.l.7 U - User Interrupt
Default: u-
The U directive controls user interrupts. When active, {$U+}, the user may in-
terrupt the program anytime during execution by entering a Ctrl-C. When pas-
sive, {$U-}, this has no effect. Activating this directive will significantly slow
down execution speed.
SUMMARY OF COMPILER DIRECTIVES 215
E.2 CP/M-BO Compiler Directives
The following directives are unique to the CP/M-80 implementation.
E.2.1 A - Absolute Code
Default: A+
The A directive controls generation of absolute, i.e. non-recursive, code.
When active, [$A+], absolute code is generated. When passive, [$A-], the
compiler generates code which allows recursive calls. This code requires
more memory and executes slower. For further information, see sections
8 and 16.
E.2.2 W - Nesting of With Statements
Default: W2
The W directive controls the level of nesting of With statements, i.e. the
number of records which may be 'opened' within one block. The W must
be immediately followed by a digit between 1 and 9. For further details,
please refer to section 11.2.
E.2.3 X - Array Optimization
Default: X+
The X directive controls array optimization. When active, [$X+], code
generation for arrays is optimized for maximum speed. When passive,
[$X-], the compiler minimizes the code size instead. This is discussed
further in section 10.1.
216 TURBO Pascal Language Manual
K - Stack Checking E.3.1
E.3 CP/M-a6/ MS-DOS / PC-DOS Compiler Directives
The following directive is unique to the CP/M-86 / MS-DOS implementa-
tions:
£.3.1 K - Stack Checking
Default: K+
The K directive controls the generation of stack check code. When active,
t$K +}, a check is made to insure that space is available for local variables on
the stack before eack call to a subprogram. When passive, {$K-}, no checks
are made.
SUMMARY OF COMPILER DIRECTIVES 217
E.3.1 K - Stack Checking
Notes:
218 TURBO Pascal Language Manual
TURBO Vs. STANDARD PASCAL F
F. TURBO VS. STANDARD PASCAL
The TURBO Pascal language closely follows the Standard Pascal defined by
Jensen & Wirth in their User Manual and Report, with only minor differen-
cies introduced for the sheer purpose of efficieny. These differencies are desc-
ribed in the following. Notice that the extensions offered by TURBO Pascal
are not discussed.
F.1 Dynamic Variables
Dynamic variables and pointers use the standard procedures New, Mark, and
Release instead of the New and Dispose procedures suggested by Standard
Pascal. Primarily this deviation from the standard is far more efficient in terms
of execution speed and required support code, and secondly it offers compati-
bility with other popular Pascal compilers (e.g. UCSD Pascal).
The procedure New will not accept variant record specifications. This restric-
tion, however, is easily circumvented by using the standard procedure Get-
Mem.
F.2 Recursion
CP/M -80 version only: Because of the way local variables are handled dur-
ing recursion, a variable local to a subprogram must not be passed as a var-
parameter in recursive calls.
F.3 Get and Put
The standard procedures Get and Put are not implemented. Instead, the Read
and Write procedures have been extended to handle all I/O needs. The reason
for this is threefold: Firstly Read and Write gives much faster I/O, secondly
variable space overhead is reduced, as file buffer variables are not required,
and thirdly the Read and Write procedures are far more versatile and easier to
understand that Get and Put.
TURBO Vs. STANDARD PASCAL 219
FA Goto Statements
F.4 Goto Statements
A goto statement must not leave the current block.
F.S Page Procedure
The standard procedure Page is not implemented, as the CP/M operating sy-
stem does not define a form-feed character.
F.S Packed Variables
The reserved word packed has no effect in TURBO Pascal, but it is still allo-
wed. This is because packing occurs automatically whenever possible. For the
same reason, standard procedures Pack and Unpack are not implemented.
F.7 Procedural Parameters
Procedures and functions cannot be passed as parameters.
220 TURBO Pascal Language Manual
COMPILER ERROR MESSA GES G
G. COMPILER ERROR MESSAGIES
The following is a listing of error messages you may get from the compiler.
When encountering an error, the compiler will always print the error number
on the screen. Explanatory texts will only be issued if you have included error
messages (answer V to the first question when you start TURBO).
Many error messages are totally self-explanatory, but some need a little ela-
boration as provided in the following.
01 ';' expected
02 ':' expected
03 ' " expected
04 '(' expected
05 ')' expected
06 ' =' expected
07 ': =' expected
08 '[' expected
09 ']' expected
10 ' .' expected
11 '.: expected
12 BEGIN expected
13 DO expected
. 14 END expected
1 5 0 F expected
17 TH EN expected
18 TO or DOWNTO expected
20 Boolean expression expected
21 File variable expected
22 I nteger constant expected
23 I nteger expression expected
24 Integer variable expected
25 Integer or real constant expected
26 I nteger o ~ real expression expected
27 I nteger or real variable expected
28 Pointer variable expected
29 Record variable expected
30 Simple type expected
Simple types are all scalar types, except real.
31 Simple expression expected
32 String constant expected
COMPILER ERROR MESSA GES 221
G COMPILER ERROR MESSAGES
33 String expression expected
34 String variable expected
35 Textfile expected
36 Type identifier expected
37 Untyped file expected
40 Undefined label
A statement references an undefined label.
41 Unknown identifier or syntax error
Unknown label, constant, type, variable, or field identifier, or syntaxt
error in statement.
42 Undefined pointer type in preceding type definitions
A preceding pointer type definition contains a reference to an unk-
nown type identifier.
43 Duplicate identifier or label
This identifier or label has already been used within the current
block.
44 Type mismatch
1) Incompatible types of the variable and the expression in an as-
signment statement 2) Incompatible types of the actual and the for-
mal parameter in a call to a subprogram. 3) Expression type incom-
patible with index type in array assignment. 4) Types of operands in
an expression are not compatible.
45 Constant out of range
46 Constant and CASE selector type does not match
47 Operand type(s) does not match operator
E.g. 'A' div '2'
48 I nvalid result type
Valid types are all scalar types, string types, and pointer types.
49 Invalid string length
The length of a string must be in the range 1 .. 255.
50 String constant length does not match type
51 Invalid subrange base type
Valid base types are all scalar types, except real.
52 Lower bound )" upper bound
The ordinal value of the upper bound must be greater than or equal
to the ordinal value of the lower bound.
53 Reserved word
These may not be used as identifiers.
54 Illegal assignment
55 String constant exceeds line
String constants must not span lines.
222 TURBO Pascal Language Manual
COMPILER ERROR MESSA GES G
56 Error in integer constant
An Integer constant does not conform to the syntax described in
section 4.2, or it is not within the Integer range -32768 .. 32767.
Whole Real numbers should be followed by a decimal point and a
zero, e.g. 123456789.0.
57 Error in real constant
The syn.tax of Real constants is defined in section 4.2.
58 Illegal character in identifier
60 Constants are not allowed here
61 Files and pointers are not allowed here
62 Structured variables are not allowed here
63 Textfiles are not allowed here
64 Textfiles and untyped files are not allowed here
65 Untyped files are not allowed here
66 I/O not allowed here
Variables of this type cannot be input or output.
67 Files must be VAR parameters
68 File components may not be files
file of file constructs are not allowed.
69 I nvalid ordering of fields
70 Set base type out of range
The base type of a set must be a scalar with no more than 256 pos-
sible values or a subrange with bounds in the range 0 .. 255.
71 Invalid GOTO
A GOTO cannot reference a label within a FOR loop from outside
that FOR loop.
72 Label not within current block
A GOTO statement cannot reference a label outside the current
block.
73 Undefined FORWARD procedure(s)
A subprogram has been forward declared, but the body never
occurred.
74 INLINE error
75 Illegal use of ABSOLUTE
1) Only one identifier may appear before the colon in an absolute
variable declaration. 2) The absolute clause may not be used in a
record.
90 File not found
The specified include file does not exist.
91 Unexpected end of source
Your program cannot end the way it does. The program probably
has more begins than ends.
COMPILER ERROR MESSA GES 223
G COMPILER ERROR MESSAGES
97 Too many nested WITHs
Use the W compiler directive to increase the maximum number of
nested WITH statements. Default is 2. (CP/M-SO'only).
98 M emory overflow
You are trying to allocate more storage for variables than is avai-
lable.
99 Compiler overflow
There is not enough memory to compile the program. This error may
occur even if free memory seems to exist; it is, however, used by the
stack and the symbol table during compilation. Break your source
text into smaller segments and use include files.
224 TURBO Pascal Language Manual
RUN-TIME ERROR MESSAGES H
H. RUN-TIME ERROR MESSAGES
Fatal errors at run-time result in a program halt and the display of the mes-
sage:
Run-time error NN, PC=addr
Program aborted
where NN is the run-time error number, and addr is the address in the pro-
gram code where the error occurred. The following contains explanations of
all run-time error numbers. Notice that the numbers are hexadecimal!
01 Floating point overflow.
02 Division by zero attempted.
03 Sqrt argument error.
The argument passed to the Sqrt function was negative.
04 Ln argument error.
The argument passed to the Ln function was zero or negative.
10 String length error.
1) A string concatenation resulted in a string of more than 255 cha-
racters. 2) Only strings of length 1 can be converted to a character.
11 I nvalid string index.
Index expression is not within 1 .. 255 with Copy, Delete or Insert
procedure calls.
90 I ndex out of range.
The index expression of an array subscript was out of range.
91 Scalar or subrange out of range.
The value assigned to a scalar or a subrange variable was out of
range.
92 Out of integer range.
The real value passed to Trunc or Round was not within the Integer
range -32767,.32767.
FF Heap/stack collision.
A call was made to the standard procedure New or to a recursive
subprogram, and there is insufficient free memory.
RUN-TIME ERROR MESSAGES 225
H RUN-TIME ERROR MESSAGES
Notes:
226 TURBO Pascal Language Manual
I/O ERROR MESSAGES
o. % ERROR MESSAGES
An error in an input or output operation at run-time results in in I/O error. If
I/O checking is active (I compiler directive active), an I/O error causes the
program to halt and the following error message is displayed:
I/O error NN, PC=addr
Program aborted
where NN is the I/O error number, and addr is the address in the program
code where the error occurred.
If I/O error checking is passive (1$1-}), an I/O error will not cause the program
to halt. I nstead, all further I/O is suspended until the result of the I/O opera-
tion has been examined with the standard function 10result. If I/O is attemp-
ted before 10result is called after en error, a new error occurs, possibly hang-
ing the program.
The following contains explanations of all run-time error numbers. Notice that
the numbers are hexadecimal!
01 File does not exist.
The file name used with Reset. Erase, Rename, Execute, or Chain
does not specify an existing file.
02 File not open for input.
1) You are trying to read (with Read or Readln) from a file without a
previous Reset or Rewrite. 2) You are trying to read from a text file
which was prepared with Rewrite (and thus is empty). 3) You are
trying to read from the logical device LST:, which is an output-only
device.
03 File not open for output.
1) You are trying to write (with Write or Writeln) to a file without a
previous Reset or Rewrite. 2) You are trying to write to a text file
which was prepared with Reset. 3) You are trying to write to the lo-
gical device KB 0:, which is an input-only device.
I/O ERROR MESSAGES 227
I/O ERROR MESSAGES
04 File not open.
You are trying to access (with BlockRead or BlockWrite) a file with-
out a previous Reset or Rewrite.
10 Error in numeric format.
The string read from a text file into a numeric variable does not con-
form to the proper numeric format (see section 4.2).
20 Operation not allowed on a logical device.
You are trying to Erase, Rename, Execute, or Chain a file assigned to
a logical device.
21 Not allowed in direct mode.
Programs cannot be Executed or Chained from a program running in
direct mode (Le. a program activated with a Run command while
the Memory compiler option is set).
22 Assign to std files not allowed.
90 Record length mismatch.
The record length of a file variable does not match the file you are
trying to associate it with.
91 Seek beyond end-of-file.
99 Unexpected end-of-file.
1) Physical end-of-file encountered before EOF-character (Ctrl-Z)
when reading from a text file. 2) An attempt was made to read
beyond end-of-file on a defined file. 3) A Read or BlockRead is
unable to read the next sector of a defined file. Something may be
wrong with the file, or (in the case of BlockRead) you may be trying
to read past physical EOF.
FO Disk write error.
Disk full while attempting to expand a file. This may occur with the
output operations Write, WriteLn, Block Write, and Flush, but also
Read, ReadLn, and Close may cause this error, as they cause the
write buffer to 'be flushed.
F1 Directory is full.
You are trying to Rewrite a file, and there is no more room in the
disk directory.
F2 File size overflow.
You are trying to Write a record beyond 65535 to a defined file.
FF File disappeared.
An attempt was made to Close a file which was no longer present in
the disk directory, e.g. because of an unexpected disk change.
228 TURBO Pascal Language Manual
TRANSLATING ERROR MESSAGES J
J. TRANSLATING ERROR MESSAGES
The compiler error messages are collected in the file TURBO. MSG. These
messages are in English but may easily be translated into any other language
as described in the following.
The first 24 lines of this file define a number of text constants for subsequent
inclusion in the error message lines: a technique which drastically reduces the
disk and memory requirements of the error messages. Each constant is identi-
fied by a control character, denoted by a ~ character in the following listing.
The value of each constant is anything that follows on the same line. All cha-
racters are significant. also leading and trailing blanks.
The remaining lines each contain one error message, starting with the error
number and immediately followed by the message text. The message text
may consist of any characters and may include previously defined constant
identifiers (control characters). Appendix G lists the resulting messages in full.
When you translate the error messages, the relation between constants and
error messages will probably be quite different from the English version listed
here. Start therefore with writing each error mesage in full, disregarding the
use of constants. You may use these error messages, but they will require ex-
cessive space. When all messages are translated, you should find as many
common denominators as possible. Then define these as constants at the top
of the file and include only the constant identifiers in subsequent message
texts. You may define as few or as many constants as you need, the restric-
tion being only the number of control characters.
As a good example of the use of constants, consider errors 25,26, and 27.
These are defined exclusively by constant identifiers, 15 in total, but would re-
quire 101 characters if written in clear text.
The TURBO editor may be used to edit the TURBOMSG.OVR file. Control
characters are entered with the Ctrl-P prefix, i.e. to enter a Ctrl-A ( ~ A) into
the file, hold down the (CONTROl) key and press first p, then A. Control cha-
racters appear dim on the screen (if it has any video attributes).
Notice that the TURBO editor deletes all trailing blanks. The original message
therefore does not use trailing blanks in any messages.
TRANSLA TlNG ERROR MESSAGES 229
J.1 Error Message File Usting
J.1 Error Message File Listing
are not allowed
can not be
constant
does not
expression
identifier
file
here

Ie

or

match
real

Ie
out of range
variable
overf low
expected
type
[ Inval id
pOinter
01';
02':
03',
04' (

06' ='
07' : ='
08' [
09']
10'.
11' ..







230 TURBO Pascal Language Manual
Error Message File listing
21






28Po int e X

308







label
syntax error
in definitions
label
44Type mismatch

and CASE
operator
[ resul t
length

subrange
52Lower bound > upper bound
53Reserved word
assignment
exceeds line
56Error in
57Error
character


62St

and


must parameters
TRANSLATING ERROR MESSAGES
J.1
231
J.1

of fields
70Set
GOTO
72Label not within current block
FORWARD procedure(s)
74INLINE error
use of ABSOUITE
not found
91Unexpected end of source
97Too many nested WITH's

99Compi
232
Error Message File Usting
TURBO Pascal Language Manual
TURBO SYNTAX K
K. TURBO SYNTAX
The syntax of the TURBO Pascal language is presented here using the forma-
lism known as the Backus-Naur Form. The following symbols are meta-
symbols belonging to the BNF formalism, and not symbols of the TURBO
Pascal language: .
I
{}
Means "is defined as".
Means "or".
Enclose items which may be repeated zero or more times.
All other symbols are part of the language. Each syntactic construct is printed
in italics, e.g.: block and case -element. reserved words are printed in bold-
face, e.g.: array and for.
actual-parameter :: = expression I variable
adding-operator :: = + I - I or I xor
array-constant :: = (structured-constant { , structured-constant} )
array-type :: = array [index-type { , index-type} ] of component-type
array-variable :: = variable
assignment-statement :: = variable: = expression I
function-identifier :: = expression
base-type :: = simple-type
block :: = declaration-part statement-part
case-element :: = case-list :statement
case -label :: = constant
case-label-list :: = case-label { , case-label}
case-list :: = case-list-element {, case-list-element}
case-list-element :: = constant I constant .. constant
case-statement :: = case expression of case-element { ; case-element} end
I case expression of case-element { ; case-element}
otherwise statement { ; statement} end
complemented-factor :: = signed-factor I not signed-factor
component-type :: = type
component-variable :: = indexed-variable I field-designator
compound-statement :: = begin statement { ; statement } end
conditional-statement :: = if-statement I case -statement
constant :: = unsigned-number I sign unsigned-number I constant-identifier
I sign constant-identifier I string
TURBO SYNTAX 233
K
constant-definition-part :: = const constant-definition
{ ; constant-definition} ;
constant-definition :: = untyped-constant-definition 1
typed -constant -definition
constant-identifier :: = identifier
control-character :: = @ unsigned-integer IA character
control-variable :: = variable-identifier
declaration -part :: = {declaration -section}
TURBO SYNTAX
. declaration -section :: = label-declaration -part 1 constant-definition -part
1 type-definition-part 1 variable-declaration-part 1
procedure -and -function -declaration -part
digit :: = 0 11 1 2 1 3 14 1 5 1 6 1 7 1 8 1 9
digit-sequence :: = digit {digit}
empty:: =
empty-statement :: = empty
entire-variable :: = variable-identifier I typed-constant-identifier
expression :: = simple -expression {relational-operator simple -expression}
factor :: = variable I unsigned-constant I (expression) 1
function -designator 1 set
field-designator :: = record-variable. field-identifier
field-identifier :: = identifier
field-list :: = fixed-part I fixed-part; variant-part I variant-part
file-identifier :: = identifier
file -identifier-list :: = empty I ( file -identifer { ,file -identifer }
file-type :: = file of type
final-value :: = expression
fixed-part :: = record-section { ; record-section}
for-list :: = initial-value to final-value I initial-value downto final-value,
for-statement :: = for control-variable: = for-list do statement
formal-parameter-section :: = parameter-group I var parameter-group
function-declaration :: = function-heading block;
function -designator :: = function -identifier I function -identifer
(actual-parameter { ,actual-parameter} )
function -heading :: = function identifier: result-type; I
function identifier (formal-parameter-section
{ ,formal-para meter-section } ) : result -type;
function -identifier:: = identifer
goto -statement :: = goto label
hexCtigit :: = digit I A I B I C I 0 I ElF
hexdigit-sequence :: = hexdigit {hexdigit }
identifier :: = letter {/etter-or-digit }
-.., identifier-list :: = identifier { ,identifier}
if-statement :: = if expression then statement { else statement}
index-type :: = simple-type
234 TURBO Pascal Language Manual
TURBO SYNTAX
indexed-variable :: = array-variable [ expression { ,expression} ]
initial-value :: = expression
inline-list-element :: = unsigned-integer I constant-identifier I
variable -identifier I location -counter-reference
inline-statement :: = inlineinline-list-element { ,inline-list-element }
label :: = letter-or-digit {Ietter-or-digit }
label-declaration -part :: = label label { , label} ;
letter :: = A I B I C I DIE I FIG I H II I J I K I LIM I
NIOIPIQIRISITIUIVIWIXIYIZI
alblcidielflglhliljlkillmi
nlolplqlrlsltlulvlwlxlylzl __
letter-or-digit :: = letter I digit
location-counter-reference :: =. I • sign constant
multiplying-operator :: = * 1/ I div I mod I and Ishl Ishr
parameter-group :: = identifier-list: type-identifier
pointer-type :: = ~ type-identifier
pointer-variable :: = variable
procedure-and-function-declaration-part :: =
K
{procedure -or-function -declaration }
procedure-declaration :: = procedure-heading block;
procedure-heading :: = procedure identifier ; I procedure identifier
( formal-parameter-section
{ , formal-parameter-section } ) ;
procedure-or-function-declaration :: = procedure-declaration I
function -declaration
procedure-statement :: = procedure-identifier Iprocedure-identifier
( actual-parameter { , actual-parameter} )
program-heading :: = empty I program program-identifier
file -identifier-list
program :: = program-heading block.
program-identifier :: = identifier
record-constant :: = (record-constant-element
{ ; record-constant-element } )
record-constant-element :: = field-identifier: structured-constant
record-section :: = empty I field-identifier { , field-identifier} : type
record-type :: = record field-list end
record-variable :: = variable
record-variable-list :: = record-variable { , record-variable}
referenced-variable :: = pointer-variable ~
relational-operator :: = = I <> 1<= I> = I < I> I in
repeat-statement :: = repeat statement { ; statement} until expression
repetitive -statement :: = while -statement I repeat-statement I for-statement
result-type :: = type-identifier
scalar-type :: = (identifier { , identifier} )
TURBO SYNTAX 235
K
scale -factor :: = digit-sequence 1 sign digit-sequence
set :: = [ {set-element} ]
set-constant :: = [ {set-constant-element } ]
set-constant-element :: = constant 1 constant .. constant
set-element :: = expression 1 expression .. expression
set-type :: = set of base-type
sign :: = + 1-
signed-factor :: = factor 1 sign factor
TURBO SYNTAX
simple -expression :: = term {adding-operator term}
simple-statement :: = assignment-statement Iprocedure-statement 1
goto -statement 1 inline -statement 1 empty-statement
simple-type :: = scalar-type Isubrange-type 1 type-identifier
statement :: = simple-statement 1 structured-statement
statement-part :: = compound-statement
string :: = {string-element }
string-element :: = text-string 1 control-character
string-type :: = string [ constant ]
structured-constant :: = constant 1 array-constant 1 record-constant 1
set-constant
structured-constant-definition :: = identifier: type = structured-constant
structured-statement :: = compound-statement 1 conditional-statement 1
repetitive -statement 1 with -statement
structured-type :: = unpacked-structured-type 1
packed unpacked-structured-type
subrange -type :: = constant .. constant
tag-field :: = empty 1 field-identifier:
term :: = complemented-factor {multiplying-operator complemented-factor}
text-string :: = . {character} •
type-definition :: = identifier = type
type -definition -part:: = type type -definition { ; type -definition} ;
type-identifier :: = identifier
type ::= simple-type Istructured-type Ipointer-type
typed-constant-identifier :: = identifier
unpacked-structured-type :: = string-type 1 array-type 1 record-type 1
set-type 1 file-type
unsigned-constant :: = unsigned-number Istring 1 constant-identifier 1 nil
unsigned-integer :: = digit-sequence 1 $ hexdigit-sequence
unsigned-number :: = unsigned-integer 1 unsigned-real
unsigned-real :: = digit-sequence. digit-sequence 1
digit-sequence. digit-sequence E scale-factor 1
digit-sequence E scale-factor
untyped-constant-definition :: = identifier = constant
variable :: = entire-variable 1 component-variable Ireferenced-variable
236 TURBO Pascal Language Manual
TURBO SYNTAX
variable -declaration :: = identifier-list: type I
identifier-list: type absolute constant
variable-declaration-part :: = var variable-declaration
{ ; variable-declaration} ;
variable-identifier :: = identifier
variant :: = empty I case-label list : (field-list)
variant-part :: = case tag-field type-identifier of variant { ; variant }
while -statement :: = while expression do statement
with-statement :: = with record-variable-list do statement
TURBO SYNTAX
K
237
K TURBO SYNTAX
Notes:
238 TURBO Pascal Language Manual
ASCII TABLE L
L. ASCII TABLE
DED HEX CHAR DED HEX CHAR DED HEX CHAR DED HEX CHAR
0 00
NUL
32 20 SPC 64 40 @ 96 60
1 01
SOH
33 21 ! 65 41 A 97 61 a
2 02
STX
34 22
..
66 42 B 98 62 b
3 03
EI'X
35 23 u 67 43 C 99 63 c
4 04
EDT
36 24 $ 68 44 D 100 64 d
5 05
mQ
37 25 % 69 45 E 101 65 e
6 06
ACK
38 26 8e 70 46 F 102 66 f
7 07
BEL
39 27
,
71 47 G 103 67
g
8 08
BS
40 28
(
72 48 H 104 68 h
9 09
I HI'
41 29
)
73 49 I 105 69 i
10 8A
LF
42 2A
*
74 4A J 106 6A j
11 0B
VT
43 2B
+ 75 4B K 107 6B k
12 C:XJ
FF
44 2C , 76 4C L 108 6C 1
13 0D
CR
45 2D - 77 4D M 109 6D m
14 0E
SO
46 2E 78 4E N 110 6E n
15 0F
SI
47 2F
/
79 4F 0 III 6F 0
16 10
DLE
48 30 0 80 50 P 112 70
P
17 11 001
49 31 1 81 51 Q 113 71 q
18 12
002
50 32 2 82 52 R 114 72 r
19 13
003
51 33 3 83 53 S 115 73 s
20 14
004
52 34 4 84 54 T 116 74 t
21 15
NAK
53 35 5 85 55 U 117 75 u
22 16
8YN
54 36 6 86 56 V 118 76 v
23 17
ErE
55 37 7 87 57 W 119 77 w
24 18
CAN
56 38 8 88 58 X 120 78 x
25 19
:EM
57 39 9 89 59 Y 121 79
Y
26 lA
SUB
58 3A : 90 5A Z 122 7A z
27 IB
ESC
59 3B ; 91 5B
[
123 7B
{
28 lC
FS
60 3C < 92 5C \ 124 7C I
29 ID
GS
61 3D
=
93 5D
]
125 7D
}
30 IE
RS
62 3E > 94 5E

126 7E
-
31 IF

-
US 63 3F
?
95 5F
-
127 7F DEL
ASCII TABLE
239
L ASCII TABLE
Notes:
240 TURBO Pascal Language Manual
HELP!!! M
M. HELP!! !
This appendix lists a number of the most commonly asked questions and their
answers.
0: How do I use the system?
A: Please read the manual, specifically chapter 1 .
0: Is TURBO an interpreter like UCSD?
A: No, it generates ultra-fast machine code.
0: Do I need TURBO to run programs developed in TURBO Pascal?
A: No, you can make a .COM or .CM D file.
0: How many lines of code can the compiler handle.
A: No limit. The object code, however, cannot exceed 64 KB.
0: How many significant digits does TURBO support in floating point?
A: 11.
0: Why do I get garbage on the screen when I start the TURBO editor.
A: You have not installed TURBO for your systel'!1.
0: What do I do when I run out of space using the editor?
A: Split your source code (see chapter 17 on include files).
0: What do I do when I run out of space while compiling?
A: Use the$1 directive and/or generate a .COM or .CMD file.
0: How do I make a .COM or .CMD file?
A: Type 0 from the main menu, then type C.
0: What do I do if I run out of space anyway?
A: Use the Chain facility described in sections A.1 0 and B.1.9 .
0: What do I do when the compiler generates too much code?
A: Read the appendicies about compiler switches and .CHN files.
HELP!!! 241
M HELP!!!
Q: Why don't Eofand Eoln work?
A: Set the B compiler directive off: {$B-l.
Q: I don't want Ctrl-C to stop my program, or Ctrl-S to stop screen output.
How do I prevent that?
A: Set the C compiler directive off: {$C-l.
Q: Why do my recursive procedures not work?
A: Set the A compiler directive off: {$A-l (CP/M-SO only).
242 TURBO Pascal Language Manual
TERMINAL INSTALLATION N
N. TEIRMINAL DNSTAlLATOON
Before you use TURBO Pascal, it must be installed to your particular termi-
nal, i.e. provided with information regarding control characters required for
certain functions. This installation is easily performed using the program
TlNST which is described in this chapter.
After having made a work-copy, please store your distribution diskette safely
away and work only on the copy.
Now start the installation by typing TlNST at your terminal. Select Screen in-
stallation from the main menu. Depending on your version of TURBO Pascal,
the installation proceeds as described in the following two sections.
N.1 IBM PC Display Selection
If you use TURBO Pascal without installation, the default screen set-up will
be used. You may override this default by selecting another screen mode from
this menu:
Choose one of the following displays:
0) Default display mode
1) Monochrome display
2) Color display 80x25
3) Color display 40x25
4) b/w display 80x25
5) b/w display 40x25
Which display Center no. or ~ X to exit) ~
Figure N-1: IBM PC Screen Installation Menu
Each time TURBO Pascal runs, the selected mode will be used, and you will
return to the default mode on exit.
TERMINAL INS TA LLA TlON 243
N.2 Non-IBM PC Installation
N.2 Non-IBM PC Installation
A menu listing a number of popular terminals will appear, inviting you to
choose one by entering its number:
Choose one of the following terminals:
1) ADDS 20/25/30 15) Lear-Siegler ADM-31
2) ADDS 40/60 16) Liberty
3) ADDS Viewpoint-lA 17) Morrow MOT-20
4) ADM 3A 18) Otrona Attache
5) Ampex D80 19) Qume
6) ANSI 20) Soroc IQ-l20
7) Apple/graphics 21) Soroc new models
8) Hazeltine 1500 22) Teletext 3000
9) Hazeltine Esprit 23) Televideo 912/920/925
10) IBM PC CCP/M b/w 24) Visual 200
11) IBM PC CCP/M color 25) Wyse WY-100/200/300
12) Kaypro 10 26) Zenith
13) Kaypro II and 4 27) None of the above
14) Lear-Siegler ADM-20 28) Delete a definition
Which terminal? (Enter no. or ~ x to exit):
Figure N-2: Terminal Installation Menu
If your terminal is mentioned, just enter the corresponding number, and the
installation is complete. Before installation is actually performed, you are
asked the question:
Do you want to modify the definition before installation?
This allows you to modify one or more of the values being installed as descri-
bed in the following. If you do not want to modify the terminal definition, just
type N, and the installation completes by asking you the operating frequency
of your CPU (see last item in this appendix).
If your terminal is not on the menu, however, you must define the required
values yourself. The values can most probably be found in the manual sup-
plied with your terminal.
244 TURBO Pascal Language Manual
Non-IBM PC Installation N.2
Enter the number corresponding to None of the above and answer the
questions one by one as they appear on the screen.
In the following, each command you may install is described in detail. Your
terminal may not support all the commands that can be installed. If so, just
pass the command not needed by typing RETURN in response to the prompt.
If Delete line, Insert line, or Erase to end of line is not installed, these func-
tions will be emulated in software, slowing screen performance somewhat.
Commands may be entered either simply by pressing the appropriate keys or
by entering the decimal or hexadecimal ASCII value of the command. If a
command requires the two characters 'ESCAPE' and' =', may:
either
or
Press first the Esc key, then the =. The entry will be ecchoed with
appropriate labels, i.e. <ESC> =.
Enter the decimal or hexadecimal values separated by spaces. H ex-
adecimal values must be preceded by a dollar-sign. Enter
e.g. 27 61 or $lB 61 or $lB $30 which are all equivalent.
The two methods cannot be mixed, i.e. once you have entered a non-numeric
character, the rest of that command must be defined in that mode, and vise
versa.
A hyphen entered as the very first character is used to delete a command, and
echoes the text Nothing.
Terminal type:
Enter the name of the terminal you are about to install. When you complete
TlNST, the values will be stored, and the terminal name will appear on the
initial list of terminals. If you later need to re-install TURBO Pascal to this ter-
minal, you can do that by choosing it from the list.
TERMINAL INSTALLA TlON 245
N.2 Non-IBM PC Installation
Send an initialization string to the terminal?
If you want to initialize your terminal when TURBO Pascal starts (e.g. to
download commands to programmable function keys), you answer V for yes
to this question. If not, just hit RETURN.
If you answer V, you may choose between entering the command directly or
defining a file name containing the command string. The latter is a good idea
if the initialization string is long, as e.g. a string to program a number of func-
tion keys would be.
Send a reset string to the terminal?
Here, you may define a string to be sent to the terminal when TURBO Pascal
terminates. The description of the initialization command above applies here.
CURSOR LEAD-IN command:
Cursor Lead-in is a special sequence of characters which tells your terminal
that the following characters are an address on the screen on which the cur-
sor should be placed. When you define this command, you are asked the fol-
lowing supplementary questions:
CURSOR POSITIONING COMMAND to send between line and
column:
Some terminals need a command between the two numbers defining
the row- and column cursor address.
CURSOR POSITIONING COMMAND to send after line and co-
lumn:
Some terminals need a command after the two numbers defining the
row- and column cursor address.
Column first?
Most terminals require the address on the format: first ROW, then CO-
LUMN. If this is the case on your terminal, answer N. If your terminal
wants COLUMN first, then ROW, then answerV.
OFFSET to add to LINE
Enter the number to add to the LINE (ROW) address.
246 TURBO Pascal Language Manual
Non-IBM PC Installation N.2
OFFSET to add to COLUMN
Enter the number to add to the COLUM N address.
Binary address?
Most terminals need the cursor address sent on binary form. If that is
true for your terminal, enter V. If your terminal expects the cursor ad-
dress as ASCII digits, enter N. If so, you are asked the supplementary
question:
2 or 3 ASCII digits?
Enter the number of digits in the cursor address for your termi-
nal.
CLEAR SCREEN command:
Enter the command that will clear the entire contents of your screen, both fo-
reground and background, if applicable.
Does CLEAR SCREEN also HOME cursor?
This is normally the case; if it is not so on your terminal, enter N, and define
the cursor HOME command.
DELETE LINE command:
Enter the command that deletes the entire line at the cursor position.
INSERT LINE command:
Enter the command that inserts a line at the cursor position.
ERASE TO END OF LINE command:
Enter the command that erases the line at the cursor position from the cursor
position through the right end of the line.
TERMINAL INSTALLA TlON 247
N.2 Non-IBM PC Installation
START OF 'LOW VIDEO' command:
If your terminal supports different video intensities, then define the command
that initiates the dim video here. If this command is defined, the following
question is asked:
START OF 'NORMAL VIDEO' command:
Define the command that sets the screen to show characters in
'normal' video.
Number of rows (lines) on your screen:
Enter the number of horizontal lines on your screen.
Number of columns on your screen:
Enter the number of vertical column positions on your screen.
Delay after CURSOR ADDRESS (0-255 ms):
Delay after CLEAR, DELETE, and INSERT (0-255 ms):
Delay after ERASE TO END OF LINE and HIGHLIGHT On/Off (0-255
ms):
Enter the delay in milliseconds required after the functions specified. RETURN
means 0 (no delay).
Is this definition correct?
If you have made any errors in the definitions, enter N. You will then return to
the terminal selection menu. The installation data you haver just entered will
be included in the installation data file and appear on the terminal selection
menu, but installation will not be performed.
When you enterV in response to this question, you are asked:
Operating frequency of your microprocessor in M Hz (for delays):
As the delays specified earlier are depending on the operating frequency of
your CPU, you must define this value.
The installation is finished, installation data is written to TURBO Pascal, and
you return to the outer menu (see section 1.6 ). Installation data is also saved
in the installation data file and the new terminal will appear on the terminal
selection list when you run TlNST in future.
248 TURBO Pascal Language Manual
SUBJECT INDEX
o. SUBJECT ONDtEX
A
A Note on Control Characters,
21
A-command, 175, 176
A-compiler directive, 170
Abort command, 34
Abs, 132, 206
Absolute Address Functions,
178
Absolute Code, 216
Absolute value, 132
Absolute variables, 144,
146,177
Adding operators, 51 , 53
Addr, 147, 178,209
Allocating Variables (New),
116
Arccus tangent, 132
ArcTan, 132, 206
Arithmetic functions, 132,
206
Array component, 75
Array Constants, 90
Array Definition, 75
Array of characters, 109
Array Subscript Optimization,
148
Arrays, 75, 161, 190
Arrays and Records, 165, 193
Assign, 94, 207
Assigning a value to a
pointer, 181
Assignment operator, 37
Assignment Statement, 55
Auto Indentation, 35
Auto tab on/off switch, 31
SUBJECT INDEX
18
Backspace, i 07
Backup, 16
r.AK files, 1 6
Basic Data Types, 157, 187
Basic Symbols, 37
BDOS,145
Bdos function, 153,209
Bdos procedure, 153,208
BdosHL function, 153,209
BEFORE USE, 5
Begin block, 28
Bios function, 154,209
Bios procedure, 154,208
BiosHL function, 154,209
Blanks, 39
Block, 121
Block Commands, 28
Begin block, 28
Copy block, 29
Delete block, 29
End block, 28
H ide/display block, 29
Mark single word, 28
Move block, 29
Read block from disk, 29
Write block to disk, 30
BlockRead, 112,207
B 10ckWrite, 112, 207
Boolean, 42
Brackets, 37
Byte, 41
o
249
a
C
C-command, 16, 143, 174
Call by reference, 122
Call by value, 121
Case statement, 58
Chain, 149, 182, 207
Chain and Execute, 149,182
Char, 42
Character array constants,
90
Character Arrays, 77
Character left, 23
Character right, 23
Characters, 73
Chr, 135,206
ClrScr, 127, 208
Close, 96, 207
ClrEol, 127, 208
Code segment, 175
Col(umn) indicator in editor,
18
Comment, 37, 39,45
Common Compiler Directives,
214
Common data, 150, 183
Common features, 173
Compilation in Memory, 166
Compilation To Disk, 167
Compile Command, 16
Compiler Directive Defaults,
5
Compiler Directives, 46
in include files, 142
250
A: Absolute code, 170,
216
8: I/O device selection,
107,214
8: input/output mode
selection, 1 04
C: control character
interpret, 214
I: I/O error handling,
114,214
I: Include, 15, 141
I: include files, 214
SUBJECT INDEX
K: stack check, 216
R: Range checking, 65,
73,76,215
U: user interrupt, 215
V: Type checking, 123,
215
W: With statement nesting,
216
X: Array optimization,
148,216
Compiler error messages, 221
compiler Options, 17, 143,
173
Compound Statement, 57
Concat, 71,207
Concatenation, 67
Concurrent CP/M, 176
Conditional Statements, 57
Constant Definition Part, 48
Constants
typed, 89
Control character, 10, 21,
31,32,45
Control character prefix, 34
Conversion, 65
Copy, 71,207
Copy block, 29
Cos, 132, 206
Cosine, 132
CP/M Function Calls, 153
CP/M-80 Compiler Directives,
216
CP/M -86/ MS-DOS / PC-DOS
Compiler Directives, 216
CPU stack, 170, 195
CR
as numeric input, 107
CrtExit, 1 28, 208
Crtlnit, 127, 208
Cseg,178
Ctrl-A,23
Ctrl-A in search strings, 31,
32
Ctrl-C, 214, 215
Ctrl-D,23
TURBO Pascal Language Manual
SUBJECT INDEX
Ctrl-E,23
Ctrl-F,23
Ctrl-Q Ctrl-B, 25
Ctrl-O Ctrl-C, 25
Ctrl-O Ctrl-D, 25
Ctrl-O Ctrl-E, 25
Ctrl-O Ctrl-K, 25
Ctrl-O Ctrl-P, 26
Ctrl-O Ctrl-R, 25
Ctrl-O Ctrl-S, 25
Ctrl-O Ctrl-X, 25
Ctrl-R,24
Ctrl-S,23
Ctrl-W,23
Ctrl-X, 23, 107
Ctrl-Z,24
Cursor Movement, 34
Cursor Movement Commands, 21
Character left, 23
Character right, 23
Line down, 23
Line up, 23
Page down, 24
Page up, 24
Scroll down, 24
Scroll up, 23
To beginning of block, 25
To bottom of screen, 25
To end of block, 25
To end of file, 25
To last position, 26
To left on line, 25
To right on line, 25
To top offile, 25
To top of screen, 25
Word left, 23
Word right, 23
SUBJECT INDEX
lI)
D-command, 17, 175
Data conversion, 106
Data segment, 175
Data Structures, 161, 189
Data transfer between
programs, 1 50, 183
Declaration Part, 47
Declared scalar types, 41
Defining a Pointer Variable,
115
DEL, 107
Delay, 128,208
Delete, 33, 69, 207
Delete a command, 245
Delete block, 29
Delete character under cursor,
27
Delete commands, 27
Delete character under
cursor, 27
Delete left character, 27
Delete line, 27
Delete right word, 27
Delete to end of line, 28
Delimiters, 39
DelLine, 128, 208
Deviations from standard
Pascal, 37, 47 48,58,
65,67,89,219
Digits, 37
Direct memory access, 147,
179
Direct port access, 148, 180
Directory Command, 17
Discriminated unions, 83
Disk change, 14
Disk Files, 162, 190
Disk-reset, 14
Dseg,179
Dynamic variables, 115, 219
o
251
o
E
E-command, 16, 145
Echo, 102, 104
of CR, 107,108
Edit Command, 16
Edit modes
Insert, 26
Overwrite, 26
Editing commands, 9, 19
Character left, 23
Character right, 23
Line down, 23
Line up, 23
Page down, 24
Page up, 24
Scroll down, 24
Scroll up, 23
To beginning of block, 25
To bottom of screen, 25
To end of block, 25
To end of file, 25
To last position, 26
To left on line, 25
To right on line, 25
To top of file, 25
To top of screen, 25
Word left, 23
Word right, 23
Editing of input, 107
Editor, 18
Col,18
File name, 1 9
Indent, 19
Insert, 19
Line, 18
Element (of set), 85
Else statement, 58
Empty Statement, 56
End Address, 145
End block, 28
End Edit, 35
End edit command, 30
End of line, 39
EOF,97, 106,107, 113,207
EOF with text files, 101
252
SUBJECT INDEX
Eoln, 106, 107, 207
Erase, 96, 207
Error Message File Listing,
230
Error message translation,
229
Error messages
Compiler, 221
1/0,227
run-time, 225
Execute, 149, 182, 207
eXecute Command, 17
Execution error messages, 225
Execution in Memory, 167
Execution of A Program File,
168
Exist function, 96
Exp, 133, 206
Exponential, 133
Extended File Size, 200
Extensions, 1
External procedures, 162,
191
External Subprograms, 149,
181
TURBO Pascal Language Manual
SUBJECT INDEX
f
F-command, 145, 176
False, 42
Field constants, 92
Field list, 79
Fields, 79
File handling routines, 207
File identifier, 93
File Interface Blocks, 159,
198,202
File name indicator in editor,
19
File names, 14
File of Byte, 200
File parameters, 122
File pointer, 93
File Standard Functions, 97
File type, 92, 93
File Type Definition, 93
FilePos, 97, 113, 207
Files On The Distribution
Disk, 6
FileSize, 97, 113,207
FileSize
with text files, 101
FillChar, 129,208
Find, 31
Find and replace, 32
Find Runtime Error, 145, 176
Flush, 95, 200
Flush
with text files, 101
For statement, 60
Foreign languages, 229
Forward References, 138
Frac, 133, 206
Fractional part, 133
Free memory, 175, 176
Free Unions, 83
Function Calls, 196,201
Function Declaration, 130
Function Designators, 54
Function Results, 165, 194
Functions, 130
SUBJECT INDEX
G
Get and Put, 219
GetMem, 119,208
Goto Statement, 56,220
GotoXY, 128,208
!HI
H-command, 143, 174
Halt procedure, 208
Heap, 116,170, 175,194
Heap Control Procedures and
Functions, 208
H eapPtr, 1 68, 170, 194
Hi,136
Hi function, 209
Hide/display block, 29
Highlighting, 13
Home position, 128
o
1/0,106
I/O checking, 114
I/O error handling, 114
I/O error messages, 227
I/O mode selection, 104
o
I/O Procedures and Functions, 205
I/O to textfiles, 106
IBM PC Display Selection, 243
IBM PC Screen Installation, 8
Identifiers, 43
If statement, 57
In-line M'achine Code, 152,
184
Include compiler directive,
15
Indent indicator in editor,
19
Indentation, 31
in this manual, 4
Initialized variables, 89
Input without echo, 102, 104
253
a
Input
characters, 106
editing, 107
numeric values, 107
strings, 107
Insert, 69, 207
Insert and Delete Commands,
26
Insert commands, 27
I nsert indicator in editor,
19
Insert line, 27
Insert mode on/off switch, 26
InsLine, 128, 208
Installation, 8
Installation of Editing
Commands, 9
Int, 133,206
Integer, 41,43
Integer overflow, 41
Integer part, 133
Internal Data Formats, 157,
187
Interrupt Handling, 156, 186
Intersection, 85
Intr, 186
Introduction, 1
IOresult, 114, 209
K
KeyPressed, 136, 209
254
SUBJECT INDEX
L
L-command,14 I
Label Declaration Part, 48
Labels, 56
Large programs, 141
Length, 72, 207
Length of strings, 67
Letters, 37
Limitations on sets, 85
Line break, 31
Line down, 23
Line indicator in editor, 1 8
Line Restore, 35
Line up, 23
Ln, 133, 206
Lo, 136, 209
Local variables as
var-parameters, 219
Location counter reference,
152,185
Logarithm, 133
Logged Drive Selection, 14
Logical Devices, 102
LongFilePos, 200
LongFileSize,200
LongSeek, 200
Lower case, 43
LowVideo, 129, 208
TURBO Pascal Language Manual
SUBJECT INDEX 0
ri\JiJ Miscellaneous Procedures and
M -command, 15, 143, 1 74 Functions, 208
Main File Selection, 15 Move, 129,208
Margins in this manual, 4 Move block, 29
Mark and Release, 116 Multi-user system, 95
Mark single word, 28, 34 Multidimensional Array
Maximum Free Dynamic Memory, Constants, 91
176 Multidimensional Arrays, 76
MemArray, 147, 179 Multiplying operators, 51,
MemAvail, 117, 148, 180, 52
208
Member (of se!), 85
N Memory / Com file / cHn-file,
143,174 Natural logarithm, 133
Memory access, 147, 179 Nesting of With statements,
Memory Management, 166 81,148
Memory Maps, 166 New, 116,208
Menu Nil,116
C-command, 16 Non-IBM PC Screen
D-command,17 Installation, 9, 244
E-command,16 NormVideo, 129,208
L-command,14 Not, 51,52
M -command, 15 Numbers, 43
O-command, 143, 173 Numeric input, 107
Q-command,17
R -command, 16
0 S-command,16
W-command,14 O-command, 143, 173, 175
X-command, 17 Obtaining the value of a
Minimum Code Segment Size, pointer, 181
175 Odd, 134, 206
Minimum Data Segment Size, Ofs,178
175 Oops, 3'1
Minimum Free Dynamic Memory, Operations on Files, 94, 200
175 Operations on Text Files, 100
Miscellaneous editing commands Operator precedence, 51
Abort command, 34 Operators, 51
Auto tab on/off, 31 Options, 143, 173
Control character prefix,
34
End edit, 30
Find, 31
Find and replace, 32
Repeat last find, 33
Restore line, 31
Tab, 30
SUBJECT INDEX
255
o
Options menu
C-command, 143, 174
D-command,175
E-command,145
F-command, 145, 176
H -command, 143, 174
I-command, 175, 176
M-command, 143, 174
O-command,175
S-command,144
Ord, 135, 149, 180,206,208
Ordinal value, 135
Overflow
integer, 41
real, 42
Overwrite/insert, 26
p
Packed Variables, 220
Page down, 24
Page Procedure, 220
Page up, 24
Paragraph, 175, 176
Parameters, 121, 162, 191
value, 121
variable, 122, 123
Pointer Related Items, 148,
180
Pointer symbol, 11 5
Pointer types, 92
Pointer Values, 180
Pointers, 115, 160, 164,
189, 193
Pointers and Integers, 149
Port access, 148, 1 80
Port Array, 148, 180
Pos, 72, 207
Position
with text files, 101
Pred, 134, 206
Predecessor, 134
Predefined Arrays, 77, 147,
179
Procedural Parameters, 220
256
SUBJECT INDEX
Procedure and Function
Declaration Part, 50
Procedure Declaratron, 125
Procedure Statement, 56, 121
Procedures, 125
Assign, 94
Close, 96
Delete, 69
Erase, 96
Flush, 95
Insert, 69
Read, 95
recursive, 125
Rename, 96
Reset, 94
Rewrite, 94
Seek, 95
Str,70
Val, 70
Write, 95
Program Heading, 47
Program lines, 39
Ptr, 149, 180, 208
Q
Q-command, 17
Quit Command, 17
R
R-command,16
Random, 136, 208
Random access files, 162,
199,204
Random(Num), 136
Randomize, 129, 208
Range Checking, 65
Read block from disk, 29
Read Procedure, 95, 106,
132,205
Read without echo, 102, 104
Readln Procedure, 108,132,
205
Real overflow, 42
TURBO Pascal Language Manual
SUBJECT INDEX
Reals, 42,44, 157, 163,
188, 193
Record Constants, 91
Record Definition, 79
Record type, 79
Records, 161, 190
RecurPtr, 1 68, 170
Recursion, 125, 170,216,
219
Recursion stack, 170
Recursion
Local variables as
var-parameters, 219
Relational operators, 37,
51,53
Relative complement, 85
Relaxations on Parameter Type
Checking, 123
Release procedure, 208
Rename, 96
Rename procedure, 207
Repeat last find, 33
Repeat Statement, 61
Repetitive Statements, 59
Reserved Words, 37
Reset, 94, 207
Restore line, 31
RETURN, 107
Retype, 65
Rewrite, 94, 207
Root program, 175
Round, 135,206
RUBOUT,107
Run Command, 16
Run-time error messages, 225
Run-time range checking, 65,
73, 76
SUBJECT INDEX
S
S-command, 16, 144
Save Command, 16
Scalar functions, 134, 206
Scalar Type, 63
Scalars, 157, 163, 187,
193
Scope, 125
Scope
of identifiers, 49
of labels, 56
Screen Related Procedures,
208
Scroll down, 24
Scroll up, 23
Search, 31
Seek, 95, 113,207
with text files, 101
Seg,178
Set158, 164, 189,193
Set Assignments, 88
Set Constants, 92
Set Constructors, 86
Set Expressions, 86
Set operations, 85
Set Operators, 87
Set Type Definition, 85
Shared data, 150, 183
Simple Statements, 55
Sin, 133,206
Sine, 133
SizeOf, 137,209
Space Allocation, 119
Special symbols, 37
Sqr, 134, 206
Sqrt, 134, 206
Square, 134
Square root, 134
Sseg,179
Stack, 175
StackPtr, 1 68, 170
Standard Files, 103
o
257
o
Standard Functions, 132
Abs, 132
Addr, 147, 178
ArcTan, 132
Bdos, 153
Bios, 154
BiosHL,154
Chr, 135
Cos, 132
Cseg, 178
Dseg, 179
EOF,113
Exp, 133
FilePos, 113
FileSize, 113
Frac, 133
Hi,136
Int,133
IOresult, 114
KeyPressed, 136
Ln,133
LO,136
MemAvail,117
Odd,134
Ofs, 178
Ord, 135, 149, 180
Pred,134
Ptr, 149, 180
Random, 136
Random(NumL 136
Round,135
Seg, 178
Sin,133
SizeOf,137
Sqr, 134
Sqrt, 134
Sseg, 179
Succ, 134
Swap, 137
Trunc, 135
UpCase, 137
Standard Identifiers, 38,
146, 177, 196, 201
258
SUBJECT INDEX
Standard Procedures, 127
Bdos, 153
Bios, 154
Chain, 149, 182
CirEoI,127
ClrScr, 127
CrtExit, 128
Crtlnit, 127
Delay, 128
DelUne, 128
Execute, 149, 182
FillChar, 129
GotoXY, 128
InsUne, 128
Intr, 186
LowVideo, 129
Move, 129
New,116
NormVideo, 129
Randomize, 129
Read, 106
Seek,113
Standard scalar types, 41
Start Address, 144
Starting TURBO Pascal, 7
Statement Part, 50, 55
Statement-separator, 55
Static variables, 115
Str, 70, 207
String Assignment, 68
String concatenation, 67
String Expressions, 67
String Functions, 71
String indexing, 73
String manipulation, 67
String Procedures, 69
String Procedures and
Functions, 207
String Type Definition, 67
Strings, 44, 158, 164,
188,193
Strings and Characters, 73
Structured 57
Structured Typed Constants,
90
TURBO Pascal Language Manual
SUBJECT INDEX 0
Sub-program, 121 Untyped Variable Parameters,
Subrange,59 123
Subrange Type, 64 UpCase, 137,209
Succ, 134, 206 Upper case, 43
Successor, 134 Upper left corner of screen,
Swap, 137,209 128
User Writte n I/O Drive rs,
T
155, 196, 201
Using Files, 97
Tab, 30, 35 Using Pointers, 117
Tag field, 82
Terminal installation, 9
V Text File Input and Output,
106 Val, 70, 207
Text Files, 100, 162, 191 Value Parameters, 121, 163,
The empty set, 86 192
To beginning of block, 25 Variable Declaration Part, 49
To bottom of screen, 25 219
To end of block, 25 Variable Parameters, 122,
To end of file, 25 123,163,192
To last position, 26 Variables, 49, 115
To left on line, 25 absolute, 146, 177
To right on line, 25 Variant Records, 82
To top of file, 25
To top of screen, 25
W TPA,145
Trailing blanks, 25, 34 W -command, 14
Transfer functions, 135,206 While statement, 61
Translation of error messages, With Statement, 81, 148, 180
229 Word left, 23
True, 42 Word right, 23
Trunc, 135,206 WordStar compatibility, 9
Type checking, 123 Work File Selection, 14
Type Conversion, 65 Write, 95
Type Definition Part, 49 Write block to disk, 30
Typed constants, 89 Write parameters, 109
Write Procedure, 109, 132,
IUl
205
Writeln Procedure, 111, 132,
Unary minus, 51 205
Unclusion,87
Unions, 83, 85
)(
Unstructured Typed Constants,
89 X -command, 17
Untyped Files, 112
SUBJECT INDEX 259
TURBO TOOLBOX©
POWERTOOLS FOR TURBO PASCAL
We've crafted some special tools to help you create the best
Pascal programs in the least amount of time. Designed to
compliment the power and speed of Turbo Pascal, these are
functioning modules created to save you from the "rewriting
the wheel" syndrome.
B + Trees on Disk
The fastest way to implement searches in records. Perfect
for databases, address books or any other applications where
you need to search through information for data. And on disk
means you won't be cluttering RAM. Source code included!!!
Quicksort on Disk
The fastest way to sort. Preferred by knowledgeable profes-
sionals. Available for you now with commented source code.
GINST (General Installation Program)
Now ... the programs you write with Turbo Pascal can have
a terminal installation module just like Turbo's! Saves hours
of work and research, and adds tremendous value to
everything you write.
Turbo Toolbox ©
Available May, 1984
To Order
TURBO TOOLBOX©
Mail check, money order, VISA or
MASTERCARD number and
expiration date to:
D) BORlAnD
.)) INTERNATIONAL
4113 Scotts Valley Drive
Scotts Valley, California 95066
$49.95 (plus $5 shipping and
handling for U.S. orders ... $15
shipping and handling outside
U.S.) (California residents add
6% sales tax).

Copyright Notice ©
This software package and manual are copyrighted 1983, 1984 by BORLAND INTERNATIONAL Inc. All rights reserved worldwide. No part of this publication may be reproduced, transmitted, transcribed, stored in any retrieval system, or translated into any language by any means without the express written permission of BORLAND INTERNA TlONAL Inc., 4113 Scotts Valley Drive, Scotts Valley, CA 95066, USA.

Single CPU License
The price paid for one copy of TURBO Pascal licenses you to use the product

on one CPU when and only when you have signed and returned the License
Agreement printed in this book.

Disclaimer
Borland International makes no warranties as to the contents of this manual and specifically disclaims any implied warranties of merchantability or fitness for any particular purpose. Borland International further reserves the right to make changes to the specifications of the program and contents of the manual without obligation to notify any person or organization of such changes.

Second edition, February 1984 Printed in the United States of America 987654321

INTRODUCTION ............................................. 1 The Pascal Language ......................................... 1 TURBO Pascal .............................................. 1 Structure of This Manual ..................................... 2 Typography ............................................... 3 Syntax Descriptions ......................................... 4

1. USING THE TURBO SYSTEM ............................ 5 1.1 .COM and .CM D files ..................................... 5 1.2 BEFORE USE ........................................... 5 1.3 Compiler Directive Defaults ................................ 5 1.4 Files On The Distribution Disk .............................. 6 1.5 Starting TURBO Pascal ................................... 7 1.6 Installation ............................................. 8 1.6.1 IBM PC Screen Installation ............................... 8 1.6.2 Non-IBM PC Screen Installation ........................... 9 1.6.3 Installation of Editing Commands .......................... 9 1.7 TheMenu ............................................. 13 1.7.1 Logged Drive Selection ................................. 14 1.7.2 Work File Selection .................................... 14 1.7.3 Main File Selection .................................... 15 1.7.4 Edit Command ....................................... 16 1.7.5 Compile Command .................................... 16 1.7.6 Run Command ....................................... 16 1.7.7 Save Command ...................................... 16 1.7.8 eXecute Command .................................... 17 1.7.9 Directory Command ................................... 17 1.7.10 Quit Command ...................................... 17 1.7.11 compiler Options ..................................... 17 1.8 The TURBO Editor ...................................... 18 1.8.1 The Status Line ....................................... 18 1.8.2 Editing Commands .................................... 19 1.8.3 A Note on Control Characters ............................ 21 1.8.4 Before You Start: HowTo Get Out ........................ 21 1.8.5 Cursor Movement Commands ........................... 21 1.8.5.1 Basic Movement Commands ............. ; ............. 21 1.8.5.2 Extended Movement Commands ........................ 24 1.8.6 Insert and Delete Commands ............................ 26 1.8.6.1 Insert or Overwrite? .................................. 26 1.8.6.2 Simple Insert/Delete Commands ........................ 27 1.8.6.3 Extended Delete Command ............................ 27

TABLE OF CONTENTS

I

1.8.7 Block Commands ..................................... 28 1.8.8 Miscellaneous Editing Commands ........................ 30 1.9 The TURBO editor VS. WordStar ........................... 34 1.9.1 Cursor Movement ..................................... 34 1.9.2 Mark Single Word ..................................... 34 1.9.3 End Edit ............................................ 35 1.9.4 Line Restore ......................................... 35 1.9.5 Tabulator ............................................ 35 1.9.6 Auto Indentation ...................................... 35
2. BASIC LANGUAGE ELEMENTS ......................... 37 2.1 Basic Symbols ......................................... 37 2.2 Reserved Words ....................................... 37 2.3 Standard Identifiers ..................................... 38 2.4 Delimiters ............................................ 39 2.5 Program lines .......................................... 39 3. STANDARD SCALAR TYPES ...............•........... 41 3.1 Integer ............................................... 41 3.2 Byte .......................... ',' ..................... 41 3.3 Real ............................ '..................... 42 3.4 Boolean .............................................. 42 3.5 Char ................................................. 42 4. USER DEFINED LANGUAGE ELEMENTS .....•.......... 43 4.1 Identifiers ............................................. 43 4.2 Numbers .............................................. 43 4.3 Strings ............................................... 44 4.3.1 Control Characters .................................... 45 4.4 Comments ............................................ 45 4.5 Compiler Directives ..................................... 46 PROGRAM HEADING AND PROGRAM BLOCK .......•..• 47 5.1 Program Heading ....................................... 47 Declaration Part ........................................ 47 5.2 5.2.1 Label Declaration Part ................................. 48 5.2.2 Constant Definition Part ................................ 48 5.2.3 Type Definition Part ................................... 49 5.2.4 Variable Declaration Part ............................... 49 5.2.5 Procedure and Function Declaration Part ................... 50 5.3 Statement Part ........................................ 50

5.

II

TURBO Pascal Language Manual

6. EXPRESSIONS ....................................... 51 6.1 Operators ............................................. 51 6.1.1 Unary Minus ......................................... 51 6.1.2 Not Operator ......................................... 52 6.1.3 MUltiplying Operators .................................. 52 6.1.4 Adding Operators ..................................... 53 6.1.5 RelationaIOperators ................................... 53 6.2 Function Designators .................................... 54

7.

STATEMENTS ........................................ 55

7.1 Simple Statements ..................................... 55 7.1.1 Assignment Statement .................................. 55 7.1.2 Procedure Statement .................................. 56 7.1.3 Goto Statement ...................................... 56 7.1.4 Empty Statement ..................................... 56 7.2 Structured Statements .................................. 57 7.2.1 Compound Statement .................................. 57 7.2.2 Conditional Statements ................................ 57 7.2.2.1 If Statement ........................................ 57 7.2.2.2 Case Statement ..................................... 58 7.2.3 Repetitive Statements ................................. 59 7.2.3.1 For Statement ...................................... 60 7.2.3.2 While statement .................................... 61 7.2.3.3 Repeat Statement ................................... 61
8. SCALAR AND SUBRANGE TYPES ....................... 63 Scalar Type ........................................... 63 Subrange Type ......................................... 64 Type Conversion ....................................... 65 Range Checking ........................................ 65 STRING TYPE ......................................... 67 String Type Definition ................................... 67 String Expressions ...................................... 67 String Assignment ...................................... 68 String Procedures ...................................... 69 Delete .............................................. 69 Insert .............................................. 69 Str ................................................. 70 Val ................................................ 70

8.1 8.2 8.3 8.4

9.

9.1 9.2 9.3 9.4 9.4.1 9.4.2 9.4.3 9.4.4

TABLE OF CONTENTS

III

................................................•........................................... 95 14........ 90 13. 85 12.................... 94 14........•.................... 71 9................2 Set Expressions . SETTYPE ........................4 Read .....................2.2......................5...................1 File Type Definition .................1 Array Definition ....2.5. 79 11...............2 Multidimensional Array Constants ............2 Operations on Files ............. 95 14....................3 Character Arrays ............2 Rewrite .................... 89 13...........................................•.................. FILE TYPES ........ 72 9....6 Seek ....... 96 IV TURBO Pascal Language Manual ............................ 85 12.....1 Set Type Definition .. ARRAY TYPE ..............4 Set Constants ...2......2 Multidimensional Arrays ..................................................................... ReCORD TYPE ..... 82 12............ 90 13...... 87 12....2...............1 Copy ..............3 Variant Records ................................1 Assign ..........1 Array Constants ....... 89 13.... ........................••......................... 86 12..........................2.................4 Pos ........2............5 Write ....•............5........... 91 13.........9.. 72 9............................................... 91 13........................... 93 14...2 Structured Typed Constants ......7 Flush ......2.........2. 73 10.........••.................................2 Set Operators ...1 Record Definition .................. 95 14....••.....2 With Statement ................ 93 14......................2........ 88 13................. TYPED CONSTANTS ............•............. 94 14.. 77 10........... 75 10....................................5 String Functions .. 76 10.........1 Set Constructors ... 75 10..............3 Set Assignments .6 Strings and Characters .......................2...........2.. '..... 86 12....................3 Reset .......... 77 11........ 92 14..................................1 Unstructured Typed Constants ............2............3 Record Constants ........................ 95 14.......................4 Predefined Arrays .......... 94 14...............2.................................. 71 9..........5...... 94 14..8 Close .2 Con cat ........ 79 11.............................................................3 Length .......•.. 81 11........................................•................ 71 9.. ..............

.................................................................. 125 16....3.....................................2.6 DelUne ....... PROCEDURES AND FUNCTIONS ........................7.......8 I/O checking .2.........10 NormVideo .............. 121 Relaxations on Parameter Type Checking .... 106 14........2............................ 128 16.. 127 16.............1 Procedure Declaration . 121 16...14...4 CrtExit ..........2........................................................2...4 Writeln Procedure ..... 96 14...............................6 Text File Input and Output ................. 119 16................... 112 BlockRead / BlockWrite ......6..........2.................... 100 14...3 15...2 Procedures ...................................1 ClrEol ................. 112 14.................... 108 14...................2.....5.. 114 15.........1...... 128 16.........2................ 116 Using Pointers .....2......2 ClrScr ... 117 Space Allocation ..........2............. 127 16.......................2....... 127 16...........2 FilePos ...........3 Standard Files .....5 POINTER TYPES ......... 97 14... 103 14.....4 Using Files .............7 Untyped Files .2..5 Text Files ...5... 123 16.. 97 14. 128 16......2.......................2 Readln Procedure ..........2............ 128 16...............2...................................................... 100 14....5 Delay ...................... 102 14....... 97 14................. 123 16.......1 14.......................................2...........2 Untyped Variable Parameters ...........2.................... 116 Mark and Release ........................1 EOF ..........1 OperationsonTextFiles ........ 109 14.......6...............1........2.........................1 Parameters ..2........2 15....3............ 127 16.....2 Logical Devices .......... 129 TABLE OF CONTENTS v .3 FileSize .........3.........5......................................................2 Standard Procedures .............................8 GotoXY ....... 129 16........................ 97 14............................. 115 Allocating Variables (New) .......4 15.......................2..........2..................1 Read Procedure .......... 106 14............ . 96 14........9 Erase ......1 15...................................2...3 Write Procedure ... 128 16.............................. 125 16.....6............. 97 14. 111 14....9 LowVideo ...................3 File Standard Functions ..................10 Rename .2............ 115 Defining a Pointer Variable ......3 Crtlnit ........6........... 15.........7 InsLine ........................1 16...............2....................................................................................

.......5 Random(Num") ........3. 129 16.............4. 132 16...........2.9 Sqr .................1 Function Declaration ..........3......4.............. 132 16....2.......5 Frac .....2......2...1...3....1.......................3..3..2...4.3 Odd ........2 Succ ................. 136 16...3 Transfer Functions ...2.. 132 16......2 Scalar Functions ..............2..... 133 16...... 133 16.............. 130 16...1..4...........1 Chr .........4 Random .. 134 16....3.. 135 16....3........ 136 16..........4 Exp ..3.......2.......6 SizeOf ...... 134 16....3...2.... 136 16.......................3..2.... ...............8 UpCase ...............3.. 133 16............ 135 16......2...2...3.....3..................... INCLUDING FILES ..... 136 16...........1........................2........6 Int ........2 Standard Functions ..4....1 Pred ...................4........1....2..........................................4 Trunc .3............ 129 16.............8 Sin .....................2.........3.....16.......3..2.......2 KeyPressed ...3............2......2....................................... 133 16........3..... 137 16............................... 134 16....... 129 16......2.....3....2................ 132 16.......................... 136 16...1.1 Abs ..........12 Move .2....... 133 16....4 Miscellaneous Standard Functions ..3 Lo ..........3................2. 134 16...3.......2.............................3........................... 134 16........... 132 16..2. 135 16....................................... 141 VI TURBO Pascal Language Manual ......11 Randomize ...3...........3...4 Forward References ....... 137 16........3 Round ...2......2.......................................2 ArcTan ......1 Arithmetic Functions . 135 16...3...........3..................3...2.3..... ·........................3 Cos .......2......10 Sqrt .............. 136 16.......................13 FiIiChar .........2...3.... 137 16..3....... .................2....2.................3............2 Ord .....2...............3 Functions ............ 130 16........7 Swap ... 134 16..............1 Hi .4.........4.........2................................. 138 17.................3.............3.1........................................................2.... 135 16.....3....2...............3.............7 Ln .........2................1..........2.............................1..1.................2.....

..................2 A...................................15.......15................ 147 A......2 A...................................... 161 A.. 143 A... 1 48 A................. 143 A....... 155 A..........ll A.. 149 A.....l.14 Interrupt Handling ....7 With Statements ........3 A..............................13 UserWritten I/O Drivers ....................... 159 A.... 146 Absolute Variables ........................................15.....1................ 1 57 A...........2 Start Address ...... 154 A.......1............. 148 A........l Memory / Com file / cHn-file ...2 External Subprograms ..... 162 A....A......... 148 A..................................12 CP/M Function Calls ......1 Scalars ....1 BdosH L function ......................................1........................15................................. 158 A............2 A..........1...... 157 A............15.......1 Records ...................1 MemAvail .... 157 A.......5 Predefined Arrays ..... 157 Basic Data Types ......................... 149 A.............................S A.................................12. 147 MemArray .. 160 Data Structures ...........12...........l0 Chain and Execute ...................................2.... 148 Pointers and Integers .......... 152 A......1......................8....2.l.............. 153 A...................2 Arrays ....... 1 53 A......... 144 A........................2.................3 Bios procedure and function ................................... 148 A.. 149 In-line Machine Code ......4 Addr Function ....15...... 153 Bdos procedure and function .. 145 Standard Identifiers .............15................... 156 A..15 Internal Data Formats .....6 Pointers ......... 143 A........ 162 A................. CP/M-SO ...3 End Address ...........l................................................... 154 A......12.................4 BiosHL function .....................................1 Reals .....15...............2 A................................................ 161 A... 158 File Interface Blocks ................l.....4 Find Runtime Error ..........................................l compiler Options ...................5...............1 Random Access Files . 147 A.................. 146 A........................15.....................5 A........................12....5................1............6 Array Subscript Optimization ..8........1 Port Array ......8 Pointer Related Items .3.....2.............................3 TABLE OF CONTENTS VII .......3 Disk Files ......................2 Strings .....15..... 161 A......4 Sets ..... 145 A..15.15.......................

3............. 180 B.1...........3........15.....16 MemoryManagement .................. 176 B....................................2 Compilation To Disk ..5 Dseg ...... 162 A....15...................15.......3.....................6 With Statements ........... 165 A...........16.........15..3 Seg .......3 Strings ........ .. 168 A.......1.... 178 B..........16..1...............2 Pointer Values .............3 Minimum Data Segment Size ...2......2.......1.1...1 Mem Array .. 166 A............7.........7........ 179 B............. 163 A........ 180 B...................... 164 A...4 Absolute Address Functions ..4... 167 A..2 Ofs ................1...... 178 B....... 167 A.6 Sseg .................1......1...................2 Reals ........3.... 173 B.................. 180 VIII TURBO Pascal Language Manual ... 164 A..1.1 Scalars ................................2 Port Array ...........2.3...•......5 Predefined Arrays ........................7 Pointer Related Items ... 166 A.................1.........4 Sets ... 176 B...4 Function Results ... 165 A..........5 Maximum Free Dynamic Memory .1...16.. 175 B.4 Execution of A Program File .........................4..1.....2 Value Parameters .1.......15....1..1............................. 177 B............3.........4 Minimum Free Dynamic Memory . 178 B................... 179 B..............Jtion in Memory . MS-DOS/PC-DOS and CP/M-86 ....2.. 180 B........5....................... 163 A..........15........................2........ 173 B......1....1.1 B....15.....................1......................1.......3 Absolute Variables ..3................. 175 B...1... 178 B.......4....................... 175 B..........1 Compilation in Memory ......2 Minimum Code Segment Size .......1..16................3..............................1..................2 Standard Identifiers ...........1...........................1.............................A.....................1 Memory Maps ....................................1.1........5.........1.....3.....1........ 177 B.15............4..3 Parameters .............2 The Heap and The Stacks .........16..1 Common features ..... 162 A..3 Exeq.............4 Cseg .......... 179 B...1...........................2....15... 164 A..........6 Find Runtime Error " ....................4...........2 Text Files ....................... 179 B. 174 B..1.....................16........6 Arrays and Records ..........4.....15..15................ 163 A...................2...........1 Compiler Options ................................1 Memory / Com file / cHn-file ...1...5 Pointers ........... 178 B... 173 B....... 170 B..........1 Variable Parameters .... 180 MemAvaii ...........................................1........1 Addr ......1............. 166 A.............................. 163 A........

1 Arrays .......1.... 190 8....4 Function Results .........3...1...........2 DataStructures .12.....1 8asicDataTypes . 193 8.................11 Interrupt Handling .....................7. 191 8......1 Scalars ...1.5 Pointers .............3.2...............2............4 TextFiles ...2 Reals ..2 File of 8yte .. 182 8................3......12..8....1 Extended File Size .2..................................2..........1................1...2 Records ...................1 Standard Identifiers ....2............ 188 8....5 Pointers ...12.............. 198 8....1........................................1....12...1..........5 TheHeapandTheStacks ..12. 200 TABLE OF CONTENTS IX . 181 8.........................2 Reals ..........1 Intrprocedure ........... 193 8........ 181 8....1....1.... 187 8.2...............................12.3................2..... 189 8.12.......3....... 190 8.......1............1.. 200 8....................1.1 Scalars . 193 8......3 Strings ................12....12..................3 Flush Procedure .... 193 8....1 Variable Parameters ...........................................................1.....................8 External Subprograms ........ 192 8..............1...........1............6 Arrays and Records . 196 8.......2 ObtainingTheValueofa Pointer ..2....1. 189 8... 200 8.......12.6... 194 8.4 Sets ....6 Operations on Files .......................2.1 AssigningaValuetoaPointer ........2..2.........12....1..1......2................3.......... 189 8..........3 Strings .......12...12...............1.. 186 8.................12.............. 190 8...........3 Parameters ......12.12..........10 In-line Machine Code .........1......................1......... 196 8.1......2 Function Calls ................... 184 8.............. 187 8...............1.. 191 8....3.2.12........................................ 196 8................................12.....2.....1......................2..... 193 8..........................................12..............7..............12..12............2.......9 Chain and Execute ...........1....1.......... 187 8.1..2..4 File Interface 810cks .........11.....3 Disk Files .... 194 8..............1..........2..................12 Internal Data Formats ...6....2 The MS-DOS / PC-DOS Implementations ............5 Random Access Files ..2..4 Sets ......3......3 UserWritten I/O Drivers ....12....... 192 8................. 193 8...1.. 196 8...................................1.2 Value Parameters ................1..............1. 181 8... 199 8.1.1.......2........... 200 8..................2..................... 186 8......6..... 188 8....

..............7 U ...................... 214 E.. 214 E........1 Common Compiler Directives .............1 DynamicVariables ..............................3....3 User Written I/O Drivers ......................................................Absolute Code .......... "........... TURBO VS....3 GetandPut ............... 201 B...............................Control Sand C .................... 213 E. 216 E...............................2 W ...9 Miscellaneous Procedures and Functions .............. 217 E...2 C ......................2...................5 Random Access Files ....1 A ....... 214 E.............................. 21 5 E..............B Screen Related Procedures ........ 216 E.1 K .....................1....3............... 219 F.................... SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS .. 216 E........2 Function Calls .....1..5 R-lndexRangeCheck ............................................ STANDARD PASCAL .. 220 F... 217 F.......................1 B -I/O Mode Selection ....................................................3 X -Array Optimization ....... 214 E......................Nesting of With Statements ............ 206 C.. 220 F.......... 201 B......4 I-Include Files .......... 219 FA Goto Statements ..............3A File Interface Blocks .1 Standard Identifiers ...Stack Checking .. 206 CA Transfer Functions .............. 214 E.....................6 Packed Variables ............2 CP/M-BO Compiler Directives ....3 I -I/O Error Handling ....1 Input/Output Procedures and Functions ....3................3 CP/M-B6/ MS-DOS / PC-DOS Compiler Directives .............2.................2 Arithmetic Functions .... 219 F........... 202 B.......................................User Interrupt ........................................5 String Procedures and Functions .. 20B C...........7 Procedural Parameters .................6 V ....3 Scalar Functions ................. 20B C........2........................................3 The CP/M-B6 Implementation ....................... 21 5 E..l. 205 C. 220 F.....................1............. 201 B.............2 Recursion ...... SUMMARY OF OPERATORS . 207 C..3........................................ 211 E......... 201 B... 205 C... 206 C. SUMMARY OF COMPILER DIRECTiVES .............3...... 216 E..... 220 X TURBO Pascal Language Manual .............6 File handling routines ........ 204 C........................... 207 C.1..............7 Heap Control Procedures and Functions ..........5 Page Procedure .....................1....1...........•.......... 219 F. 215 E................B................. 20B D..•........Var-parameter Type Checking .........................

......... I.. 221 RUN-TIME ERROR MESSAGES ..... 225 I/O ERROR MESSAGES . 229 Error Message File Listing ........ COMPILER ERROR MESSAGES ............ J.... 227 TRANSLATING ERROR MESSAGES ............................. 233 ASCII TABLE HELP!!! ..................... SUBJECT INDEX......... 241 N......... 239 ......... 243 N...G...................... L.............1 IBM PC Display Selection .......................... 243 N... 249 XI TURBO Pascal Language Manual ... TERMINAL INSTALLATION ........ 230 TURBO SyNTAX .... H.1 K...................................... ............................................................... J....... 244 O............... M........................2 Non-IBM PC Installation ..........................................

.............................. 103 TABLE OF CONTENTS XII ................ 168 Memory map during execution of a program file ........... 13 Editor Status Line ................................................................................................ 20 Operation of EOLN and Eof ....... 176 IBM PC Screen Installation Menu ..... 244 (LOST OlF 1rAl3lLlES 1-1 1-2 14-1 Editing Command Values ............... 8 Main Menu ............... 143 Start and End Addresses ............................................... 145 Find Run-time Error ........................................................ 12 Editing Command Overview ......................... 167 Memory map during execution in direct mode ..................................... 243 Terminal Installation Menu .........................................lOST OlF lFDGURES 1 -1 1-1 1-2 1-3 1-4 1 -5 A-1 A-2 A-3 A-4 A-5 A-6 A-7 A-8 8-1 8-2 8-3 8-4 N-1 N-2 Structure of Manual ............. 146 Memory map during compilation in memory ........................ 166 Memory map during compilation to a file ......................................................................................... 174 Run-time Error Message ......... 7 Main Menu ... 173 Memory Usage Menu ....................... 7 Installation Main Menu ....................................................................... 3 Log-on Message ....... 169 Options Menu . 144 Run-time Error Message ....... 18 Options Menu ........................................................................................... 176 Find Run-time Error .

Although making thorough use of examples. and at least a basic knowledge of Pascal is assumed. Switzerland and named in honor of Blaise Pascal. specifically introducing structured programming. published in 1971. Jensen and N. TURBO Pascal closely follows the definition of Standard Pascal as defined by K. and in the hands of a programmer it becomes an extremely effective development tool providing both compilation and execution times second to none.This book is a reference manual for the TURBO Pascal system as implemented for the CP/M-80. it is not meant as a Pascal tutorial or textbook. the requirements of all categories of users: it offers the student a friendly interactive environment which greatly aids the learning process. high level programming language originally designed by Professor Niklaus Wirth of the Technical University of Zurich. was intended to aid the teaching of a systematic approach to computer programming. Pascal is today established as one of the foremost high-level languages. Professor Wirth's definition of the Pascal language. A number of extensions are provided. The Pascal Language Pascal is a general-purpose. Among these are: Absolute address variables Bit/byte manipulation Direct access to CPU memory and data ports Dynamic strings Free ordering of sections within declaration part Full support of operating system facilities INTRODUCTION 1 . TU RBO Pascal TU RBO Pascal is designed to meet. whether the application is education or professional programming. and MS/DOS operating systems. the famous French Seventeenth Century philosopher and mathematician. CP/M -86. The few and minor differences are described in section F . Wirth in the Pascal User Manual and Report. Pascal has since been used to program almost any task on almost any computer.

Structure of This Manual As this manual describes three slightly different TURBO Pascal implementations. These include Standard Pascal and many extensions. 3: Appendices A and B describe items which have not been covered in previous chapters because they differ among implementations.In-line machine code generation I nclude files Logical operations on integers Program chaining with common variables Random access data files Structured constants Type conversion functions In addition. 2 TURBO Pascal Language Manual . an alphabetical subject index. error messages. 2: The main body of the manual. chapters 2 through 17 .). programs using them are no longer directly portable between implementations. i. the built-in editor. e. the reader should keep the following structure in mind: 1: Chapter 1 describes the installation and use of TURBO Pascal. and MS-DOS/PC-DOS. CP/M-B6. special features. CP/M-BO. These appendices mostly describe the more intricate details of programming (e.read them if you have any problems. that as these things are implementation dependent. As long as you use the language as described in these chapters.g. etc. you need only read the one appendix pertaining to your implementation. direct memory and port accesses. This information applies to all three implementations. etc. To avoid confusion. Remember. Appendix M contains some answers to the most common questions . 4: The remaining appendices are common to all implementations and contain summaries of language elements.e. your programs will be fully portable between implementations. some extra standard procedures and functions are included to further increase the versatility of TURBO Pascal. etc. user written I/O drivers. however.g. describe the common parts of TURBO Pascal. syntax diagrams. and limitations of each implementation. requirements. internal data formats. those parts of the language which are identical in all three versions. and need only be read by those who wish to use TURBO Pascal to its fullest extent.

Italics Boldface INTRODUCTION 3 . In particular. Boldface is used to mark reserved words. The meaning of the use of italics thus depends on the context. Special characters are used for the following special purposes: Typewri ter Typewriter-characters are used to illustrate program examples and screen output. pre-defined standard identifiers are printed in italics. and elements in syntax descriptions (see below) are printed in italics.The following is a graphic representation of the manual: Special features for 8 -bit systems Special features for 16 -bit systems Common appendices Figure 1: Structure of Manual Typography The body of this manual is printed in normal typeface. in the text as well as in program examples. Italics are used in general to emphasize sections of the text. Screen images are furthermore shown in rectangular fields of thin lines.

' Pascal') Concat C'TIT' . are printed in smaller type and with an extra wide margin. and that they may therefore be skipped on a first reading of this manual.Name) 4 TURBO Pascal Language Manual . 'R'. 'U'. In other words.Margins Certain sections. The syntax description shows that the word Concat must be followed by two or more string expressions. Syntax Descriptions The entire syntax of the Pascal language expressed as Backus-Naur Forms is collected in in appendix K which also describes the typography and special symbols used in these forms. and StN must be string expressions. The text will explain that St1. St2. St2 { . '0' . separated by commas and enclosed in parentheses. 'B'. This indicates that their contents is of a less important nature than the surrounding text. like this one. the following examples are legal (assuming that Name is a string variable): ConcatC'TORBO'. standard identifiers use mixed upper and lower case. StN} ) Reserved words are printed in boldface. 'RID' " Pascal') ConcatC 'T'. and elements explained in the text are printed in italics. Where appropriate syntax desctiptions are also used more specifically to show the syntax of single language elements as in the following syntax description of the function Concat: Concat (Sa.

2 BEFORE USE Before using the TURBO Pascal you should. Use a filecopy program to make the copy. a number of runtime facilities (such as indox checking and recursion) are de-selected until explicitly selectod by the programmer. it should be understood as . etc. for your own protection. PLEASE NOTICE that the default settings of these directives will optimize ol(ecution speed and minimize code size. whenever . Remember that the User's License allows you to make as many copies as you need for your own personal use and for backup purposes only. All compiler directives and their default values are described in appendix E .COM mark the executable program files in CP/M -80 and MS-DOS / PC-DOS. and make sure that all files are successfully transferred.g. Thus.CMD files Files with the extension .3 Compiler Directive Defaults TURBO Pascal provides a number of compiler directives to control special runtime facilities like e.COM -files are mentioned in the following. lUJSU rnG 1fIHJ[E 1r{UHRlBO SYSTEM This chapter describes the installation and use of the TURBO Pascal system. 1.1 . indol( checl(ing. USING THE TURBO SYSTEM 5 .USING THE TURBO SYSTEM 1). In CP/M-86 these will instead be marked .CMD.CMD if your operating system is CP/M-86. recursion (CP/m-SO only). Thus. 1. make a work-copy of the distribution diskette and store the original safely away.COM and . 1. specifically the built-in editor.

COM TINST.OVR TURBO. If present.COM TURBO. Even this file may be translated into any language desired. This message file may be edited if you wish to translate error messages into another language . you may find it an advantage to use TURBO without these error messages. this file will load. In any case. may be included on the run-time disk if so desired. as the system will automatically point out the error. A fully operative TURBO Pascal thus requires only 28 K of disk space (33 K for 16-bit systems). PAS files READ.1. and the program tnkcs you through a completely menudriven installation procedure. Errors will in that case just print out an error number. The example . Overlay file for TURBO. 6 TURBO Pascal Language Manual .4 Files On The Distribution Disk 1.MSG is needed only if you want online compile-time error messages. and the manual can be consulted to find the explanation.COM TINST. and finally all TlNST files are used only for the installation procedure. but more importantly. Text file containing error messages. Needs only be present on the run-time disk if you want to execute . Sample Pascal programs . TUST. Installation program. Terminal installation data (not present on IBM PC versions). This and the following files need not be present on your run-time disk.4 Files On The Distribution Disk The distribution disk contains the following files: TURBO.COM (CP/M-80 version only).DTA TINST. COM must to be on your run-time disk. Needs not be present on runtime disk.MSG TLlST.COM is used only to list TURBO programs on the printer.PAS files. TURBO.MSG . and the program will be up and running. but are not necessary. of course. Needs not be present on your run-time disk if you will accept the system without explanatory compile-time error messages. Just type TINST at your terminal.5 Kbytes extra memory for programs.OVR is required only if you want to be able to execute programs from the TURBO menu. Messages for the installation program. Only TURBO.more about that in appendix J Source text listing program. it gives you approx 1.ME The TURBO Pascal program. it not only saves space on the disk. When you enter the command TURBO on your terminal.COM files from TURBO. TURBO. . this file contains the latest corrections or suggestions on the use of the system.

enter the command TURBO at your terminal.86 on IBM PC PC. e. You may instead answer N and save about 1.rm . The third line tells you which screen is installed.g.5 1.[version] Copyright (C) 1983 by BORLAND International No terminal selected Include error messages (Y/N)?D Figure 1-1: Log-on Message In the first line. CP/M. the error message file will be read into memory (if it is on the disk). At the mo ment none .5 Starting TURBO Pascal When you have a copy of the system on your work-disk. If you enter a V in response to the question. The system will log on with the following message: TURBO Pascal release n. briefly displaying the message Loading TURBO. MSG.but more about that later.nn identifies your release number and [versionJ indicates the operating environment (operating system and CPU).Starting TURBO Pascal 1.5 Kbytes of memory. Then the TURBO main menu will appear: Logged drive: A Work file: Main file: Edi t eXecute Compi Ie Dir Run Quit Save compiler Options Text: G bytes Free: 62903 bytes Figure 1-2: Main Menu USING THE TURBO SYSTEM 7 . n.

All TlNST files and the TURBO.6. The values above for Logged drive and memory use are for the sake of example only.7 . and you may now continue with the Command installation described in section 1.6 Installation Type TINST to start the installation program. the command executes immediately. a menu will appear which lets you select the sCreen mode you want to use while running TURBO (see appendix N for details). Don't press <RETURN). Each command is executed by entering the associated capital letter (highlighted after terminal installation if your terminal has that feature). or Q: Figure 1-3: Installation Main Menu 1. When you have made your choice. the values shown will be the actual values for your computer. IBM PC users can use TURBO as it comes and may skip the following and go to section 1. type Q now to leave TURBO for a minute to perform the installation. This menu will appear: TURBO Pascal installation menu. each of which will be described in detail in following sections. COM file must be on the logged drive. 8 TURBO Pascal Language Manual . 1.but assuming that you do.5 Starting TURBO Pascal The menu shows you the commands available.3 or you may terminate the installation at this point by entering Q for Quit. Choose installation item from the following: [S]creen installation [C]ommand installation [Q]uit Enter S. you may use TURBO without installation if you don't plan to use the built-in editor . C.1 IBM PC Screen Installation When you hit 5 to perform Screen installation.6. the main menu reappears. If you're an non-IBM PC user.1.

6. you will answer No to this question. and you may choose the one that suits you by entering the appropriate number. and you may now continue with the Command installation described in the next section or you may terminate the installation at this point by entering Q for Quit. delete and insert text. When you hit C for Command installation. an ADM -3A compatible terminal with some additional features. but they may easily be taylored to fit your taste or your keyboard.6. Now you will be asked the operating frequency of your microprocessor. When you have chosen a terminal.6. If you answer Yes. nor compatible with any of these (note that a lot of terminals are compatible with e. Normally. the first command appears: CURSOR MOVEMENTS: 1: Character left Ctrl-S ->D USING THE TURBO SYSTEM 9 .g. A menu containing the names of the mostly used terminals will appear.3 Installation of Editing Commands The built-in editor responds to a number of commands which are used to move the cursor around on the screen. Enter the appropriate value (2. If your terminal is not on the menu. which means that you are satisfied with the pre-defined terminal installation. See appendix N for details.2 1. This is quite straightforward. you will be taken through a series of questions as described in appendix N. After that. you are asked if you want to modify the installation before installation. This can be used if you have e.Non-IBM PC Screen Installation 1.2 Non-IBM PC Screen Installation Now hit S to select Screen installation.g. move text etc. 6 or 8. most probably 4). 4. ADM -3AL then you must perform the installation yourself. but you will need to consult the manual that came with your terminal to answer the questions asked by the installation menu. 1. These commands have default values which comply with the 'standard' set by WordStar. Choose the ADM -3A and add the required commands to activate the special features. the main menu re-appears.

a left-arrow-key. You may enter a . If you want to use another command.1.Notice that the two methods cannot be mixed within one command. This may be useful to install commands which are not presently available on your keyboard. 10 TURBO Pascal Language Manual . But it's there for those who wish to use it. hexadecimal values are prefixed by a doliar-sign:$lB.g.g.(minus) to remove a command from the list.> <ESC> a II 2) Instead of pressing the actual key you want to use.e. hold down the key marked CONTROL or CTRL and press 5).> in either of two ways: 1) Simply press the key you want to use. The values of multiple characters are entered separated by spaces. i. as in WordStar. i. you may enter it following the . The installation program responds with a mnemonic of each character it receives.e. This facility has just been provided for very few and rare instances. because there is really no idea in defining a command that cannot be generated by pressing a key. your screen will look like this: CURSOR MOVEMENTS: 1: Character left Ctrl-S . you may enter the ASCII value(s) of the character(s) in the command. if you want to install the values of a new terminal while still using the old one.3 Installation of Editing Commands This tells you that the command to move the cursor one character to the left is currently a Ctrl-S (Control-S. If you have a left-arrow-key that transmits an <ESCAPE> character followed by a lower case a. In both cases. terminate your input by pressing <RETURN>. if you have it) or any other key or sequence of keys that you choose (max.6. Decimal values are just entered: 27. It could be a function key (e. if you have started defining a command sequence by pressing keys. you must define all characters in that command by pressing keys and vise versa. 4). e. and you press this key in the situation above. and a B backs through the list one item at a time.

e. and you must correct the error before terminating the installation. The following table lists the default value and the use of each command.Installation of Editing Commands 1.6. If you make an error in the installation. define the same command for two different purposes. if any. and they may all be changed to your specification.3 The editor accepts a total of 45 commands.S -> Al ternat ive Ct rl-H -> Character right Ctrl-D -> Word left Ct rl-A -> Word right Ctrl-F -> Line up Ct rl-E -> Line down Ct rl-X -> Scroll up Ctrl-W -> Scroll down Ct rl-Z -> Page up Ctrl-R -> Page down Ctrl-C -> Ctrl-Q Ctrl-S -> To left on 1 ine To right on 1 ine Ctrl-Q Ctrl-D -> Ctrl-Q Ctrl-E -> To top of page To bottom of page Ctrl-Q Ctrl-L-> Ctrl-Q Ctrl-R -> To top of file Ctrl-Q Ctrl-C -> To end of file Ctrl-Q Ctrl-B -> To beginning of block Ctrl-Q Ctrl-B -> To end of block I To last cursor position Ctrl-Q Ctrl-P -> INSERT & DELEI'E: 21: 22: 23: 24: 25: 26: 27: 28: Ctrl-V -> Insert mode on/off Ctrl-N -> Insert 1 ine Ctrl-Y -> Delete 1 ine Ctrl-Q Ctrl-Y -> Delete to end of 1 ine Ctrl-T -> Delete right word Delete character under cursor Ctrl-G -> <DEL> . CURSOR MOVEMENTS: 1: 2: 3: 4: 5: 6: 7: 8: 9: 18: 11: 12: 13: 14: 15 : 16: 17: 18: 19: 28: Character left Ct r 1.g. and space is allowed for you to mark your changes.> Delete left character Nothing -> Alternative: USING THE TURBO SYSTEM 11 . an self-explanatory error message is issued.

to use the (85) as an alternative to (DEL> if the (85) key is more conveniently located. EDITING COMMANDS: 38: 39: 40: 41 : 42: 43: 44: 45: End edit Tab Auto tab on/off Restore line Find Find & replace Repeat last find Control character prefix Ctrl-K Ct rl.I Ctrl-Q Ctrl-Q Ctrl-Q Ctrl-Q Ct rl-L Ctrl-P Ctrl-D -> Ctrl-I Ctrl-L Ctrl-F Ctrl-A -> -> ->------>------>------>------>------ Table 1-1 : Editing Command Values Items 2 and 28 let you define alternative commands to Character Left and Delete left Character commands. the two alternative commands must be unambiguous like all other commands. e.3 Installation of Editing Commands BLOCK COMMANDS: 29: 30: 31: 32: 33: 34: 35: 36: 37: Mark block begin Mark block end Mark single word Hide/display block Copy block Move block Delete block Read block from disk Write block to disk Ctrl-K Ctrl-K Ctrl-K Ctrk-K Ctrl-K Ctrl-K Ctrl-K Ctrl-K Ctrl-K Ctrl-B Ctrl-K Ctrl-T Ctrl-W Ctrl-C Ctrl-V Ctrl-Y Ctrl-R Ctrl-W -> -> -> -> -> -> -> -> -> MISC.6. Normally (85) is the alternative to Ctrl-5.g.1. 12 TURBO Pascal Language Manual . You may redefine these to suit your keyboard. Of course. and there is no defined alternative to (DEL>.

check your installation data.g.7 The Menu After installation. USING THE TURBO SYSTEM 13 . it is naturally assumed that your screen has different video attributes to show text e. A command is activated by pressing the associated upper case (highlighted) letter. the command is executed immediately. it is easily restored by entering an 'illegal command'. Don't press (RETURN).e. any key that does not activate a command. underline or some other way. (RETURN) or (SPACE) will do perfectly. this time with the command letters highlighted. If not. Logged drive: A Work file: l!ain file: Mit eXecute Campi Ie Dir Run Quit Save compiler Options Text: 0 bytes Free: 62903 bytes >D Figure 1-4: Main Menu By the way. inverse. The menu may very well disappear from the screen when working with the system.The Menu 1. you once again activate TURBO Pascal by typing the command TURBO. The following sections describe each command in detail. i. Your screen should now clear and display the menu. If not. in different intensities. whenever highlighting is mentioned here. just disregard any mention of highlighting. This menu shows you the commands available to you while working with TURBO Pascal.7 1.

If you don't want to change the current value. 1 . the following prompt is issued: New drive: • inviting you to enter a drive name.7. The W command will issue this command: Work f i Ie name: II and you may respond with any legal file name.CHN. a name of one through eight characters. just hit (RETURN). Hit e. i. The new drive is not immediately shown on the menu. even when you don't change the drive. PROGRAM. FIL becomesPROGRAM. as it is not automatically updated. When entering an L. (SPACE) to display a fresh menu which will show the new logged drive.e. TYP If you enter a file name without period and file type. an optional period.1. and an optional file type of no more than three characters: FILENAME. and . and should therefore be used whenever you change disks to avoid a fatal disk write error (CP/M only!). 14 TURBO Pascal Language Manual . optionally followed by a colon and terminated with (RETURN).RCGRAM PROGRAM. eXecute.7. the file type PAS is automatically assumed and appended to the name. PAS is not changed is not changed File types . You may explicitly specify a file name with no file type by entering a period after the name. Compile.CMD should be avoided.g.e. Run.BAK.e.2 Work File Selection The W command is used to select a work file. and Save. i. but omitting the type. as TURBO uses these names for special purposes.1 Logged Drive Selection 1 . i. a letter from A through P. the file to be used to Edit.1 Logged Drive Selection The L command is used to change the currently logged drive.COM/. .7. Examples: P. The L command performs a disk-reset.

i. USING THE TURBO SYSTEM 15 . Answer V to save or N to skip. when you hit (SPACE). If the file does not already exist.g. the current Work file is automatically saved. You can then define the Work file to be different from the Main file. The new work file name will show on the menu the next time it is updated. the file containing the error (whether it is the Main file or an include file) automatically becomes the Work file which may then be edited.e. the corrected Work file is automatically saved. and the Main file is loaded into memory. the message New Fi Ie is issued. the file which contains the include directives. and thus edit different include files while leaving the name of the Main file unchanged. If an error is found during compilation. if present. and the Work file is different from the Main file.3 Main Rle Selection The M command may be used to define a main file when working with programs which use the compiler directive $1 to include a file. When the error has been corrected and compilation is started again. The Main file should be the file which must start the compilation.7. e. If you have edited another file which you have not saved.Work File Selection 1. and the Main file is re-Ioaded. the file is read from disk. The Main file name is specified as described for the Work file name in the previous section.7. the message: Workfile X:FlLENAME. When a compilation is started.TYP not saved. 1. Save (Y/N)?D warns you that you are about to load a new file into memory and overwrite the one you have just worked on.2 When the Work file has been specified.

The compilation may result either in a program residing in memory. While you may use the TURBO system to compile and run programs without installing a terminal.4 Edit Command 1. and the editor is activated. will be renamed to . The old version of this file.8 .7.7.COM or .7.7 Save Command The S command is used to save the current Work file on disk. the use of the editor requires that your terminal be installed.BAK. 16 TURBO Pascal Language Manual . if the Work file has been edited. 1.7. it will be activated. If a compiled program is already in memory. a compilation will automatically take place following the rules above. you are first asked to specify one.1. or in a . The choice is made on the compiler Options menu described in sections A. The compilation may be interrupted at any moment by pressing a key.6 . 1.4 Edit Command The E command is used to invoke the built-in editor and edit the file defined as the Work file. The menu disappears. and the new version will be saved.COM file. the Work file will be compiled.7. The default is to have the program residing in memory. a TURBO object code file (.CMD file). If no Work file is specified. if any. If not.5 Compile Command The C command is used to activate the compiler. See section 1 .1 (16 bit systems). you will be asked whether or not to save it before the Main file is loaded and compiled. .1 (8 bit systems) and B.CHN file. In the latter case.6 Run Command The R command is used to activate a program residing in memory or. . More about the use of the editor in section 1. otherwise the Main file will be compiled. if the Cswitch on the compiler Options menu is active.1. If no Main file is specified. in a .

11 compiler Options The 0 command selects a menu on which you may view and change some default values of the compiler.10 Quit Command The Quit command is used to leave the TURBO system. you are prompted: Command: 0 You may now enter the name of uny program which will then load and run normally. control is re-transferred to TURBO Pascal. copying programs. you are prompted thus: Dir mask: 0 You may enter a drive designator or a drive designator followed by a file name or a mask containing the usual wildcards and? . 1.7. you are asked whether you want to save it before quitting. It also provides a helpful function to find run-time errors in programs compiled into object code files. USING THE TURBO SYSTEM 17 . and you return to the TURBO prompt> .7. Or you may just hit <RETURN) to get a full directory listing. Upon exit from the program.8 eXecute Command The X command lets you run other programs from within TURBO Pascal. word processors .g. If the Work file has been edited since it was loaded.7.9 Directory Command The D command gives you a directory listing and information about remaining space on the logged drive.in fact anything that you can run from your operating system.7.7. e. further discussion is deferred to appendices A and B . When hitting D.8 1. When entering X. As these options vary between implementations.eXecute Command 1. * 1. 1.

There are a few minor diferencies. you will need no further instruction in the use of the TURBO editor. Let us first take a look at the meaning of the status line at the top of the screen. If the Work file exists on the drive.8 The TURBO Editor 1. Shows the number of the column containing the cursor counted from the left side of the screen. Text is entered on the keyboard just as if you were using a typewriter. but don't worry.TYP Figure 1-5: Editor Status Line Line n Coin Shows the number of the line containing the cursor counted from the start of the file. press the <RETURN) key (or CR or ENTER or whatever it is called on your keyboard).8 The TURBO Editor The built-in editor is a screen-editor specifically designed for the creation of program text. 18 TURBO Pascal Language Manual . and the TURBO editor has a few extensions. When you have entered enough lines to fill the screen. and the editor is activated. the menu disappears.8. it is loaded and the first page of text is displayed.1 The Status Une The top line on the screen is the status line containing the following information: Line n Col n Insert Indent X:FILmAME.1. Using the TURBO editor is simple as can be: when you have defined a Work file and hit E. 1.9. as the standard definition of all commands are exactly like the ones you know from WordStar. and you may page back and forth in your text with the editing commands described later. To terminate a line. it is not lost. the top line will scroll off the screen. If it is a new file. If you are familiar with MicroPro's WordStar. the screen is blank apart from the status line at the top. these are discussed in section 1.

i. text is written as if you were using a typewriter. etc. Using the insert mode on/off command (Ctrl-V by default) will instead display the text Overwrite. etc.8. Block commands. The TURBO editor accepts a total of 45 editing commands to move the cursor around.The Status line 1. These commands can be logically grouped into the following four categories: Cursor movement commands. and type of the file being edited. I nsert and delete commands. page through the text. and Miscellaneous commands Each of these groups contain logically related commands which will be described separately in following sections.1 Indicates that characters entered on the keyboard will be inserted at the cursor position. that existing text to the right of the cursor will move to the right as you write new text. Text entered on the keyboard will then overwrite characters under the cursor instead of inserting them. and in this case specifically program writing. find and replace text strings.e. it offers you a number of editing facilities which make text manipulation. name. The following table provides an overview of the commands available: USING THE TURBO SYSTEM 19 .2 Editing Commands As mentioned before. much easier than on paper. Insert 1. but as this is a computerized text editor.8. X:FILENAME.TVP The drive. Indent Indicates that auto-indentation is in effect. It may be switched off by the auto-indent on/off command (Ctrl-Q Ctrl-I by default).

and enter E to Edit. even if you find it a bit hard in the beginning.8. Deep in the night this man/machine synthesis reaches frightening proportions. EDITING COMMANDS: End edit Tab Auto tab on/off Restore 1 ine Find Find &. once learned. specify one of the demo Pascal programs as Work file. Then try the commands as you read on. replace Repeat last find Control character prefix Table 1-2: Editing Command Overview In a case like this. quickly become so much a part of you that the editor virtually turns into an extension of your mind. the best way of learning is by doing. so start TURBO. Take it from one who has written megabytes worth of text with that editor. Hang on. It is not just by chance we have chosen to make the TURBO editor WordStar compatible .1.the logic of these commands. 20 TURBO Pascal Language Manual .2 Editing Commands CURSOR MJVEMENT COMMANDS: Character left Character right Word left Word right Line up Line down Scroll up Scroll down Page up Page down INSERT & Insert Insert De lete Delete DELEI'E COMMANDS: mode on/off 1 ine 1 ine to end of line To To To To To To To To To top of screen top of file top of file end of file left on 1 ine right on line beginning of block end of block last cursor position Delete right word Delete character under cursor Delete left character BLOCK COMMANDS: Mark block begin Mark block end Mark single word Copy block Move block Delete block Read block from disk Write block to disk Hide/display block MISC.

and _ may generate control characters for that matter). A control character is a special character generated by your keyboard when you hold down the (CONTROL) (or (CTRL» key on your keyboard and press any key from A through Z (well. F.B. 0. This command does not automatically save the file.3 I A Note on Control Characters All commands are issued using control characters. R. delete. The (CONTROL> key works like the (SHIFT) key: if you hold down the (SHIFT) key and press A.6.B. E.5 1. if you use other keys. 1.B. it might be convenient to use these.2 Each of the following descriptions consists of a heading defining the command. \. and C. followed by the default keystrokes used to activate the command. if you hold down the (CONTROL> key and press A.8. but you may find it useful to know already now that the Ctrl-K Ctrl-O command exits the editor and returns you to the menu environment.Editing Commands 1. etc. you will get a Control-A (Ctrl-A for short). ]. Plese refer to section 1.S.4 Before You Start: How To Get Out The command which takes you out of the editor is described in section 1 . 1.). USING THE TURBO SYSTEM 21 . The following descriptions of the commands assume the use of the default Word-Star compatible keystrol<es. 1. X. If you have arrow keys and dedicated word processing keys (insert. even [. The TURBO editor uses a special group of control characters to do that.B.8 .5. namely the control characters A. you will get a capital A.3 for installation details. that must be done with the Save command from the menu.1 Cursor Movement Commands Basic Movement Commands The most basic thing to learn about an editor is how to move the cursor around on the screen.8. with room in between to note which keys to use on your terminal. A.

The two last basic movement commands do not move the cursor but scrolls the entire screen upwards or downwards in the file: W E R A Z S X D C F Ctrl-W scrolls up in the file (the lines on the screen move down). only not one line at the time but a whole page. and Ctrl-D to the right. the characters are arranged in such a way on the keyboard as to logically indicate their use. Likewise with Ctrl-A and Ctrl-F: Ctrl-A moves to the left like Ctrl-S.1. Ctrl-X down.1 Basic Movement Commands Why these? Because they are conveniently located close to the control-key. 22 TURBO Pascal Language Manual . down. so that your left little finger can rest on that while you use the middle and index fingers to activate the commands. you may just hold down the control key and one of these four keys. left. Try to move the cursor around on the screen with these four commands. Ctrl-C moves the cursor down one page at a time. and Ctrl-F moves one word to the right. and right: E S D X These four characters are placed so that it is logical to assume that Ctrl-E moves the cursor up. If your keyboard has repeating keys. Furthermore. Ctrl-S to the left. Let's examine the basic movements: cursor up. and the cursor will move rapidly across the screen. Now let us look at some extensions of those movements: E R D F A 'S X C The location of the Ctrl-R next to the Ctrl-E implies that Ctrl-R moves the cursor up. and Ctrl-Z scrolls down in the file (the lines on the screen move up).5. and so it does.8. And that is exactly what they do. Similarly. but a whole word at a time.

If the cursor is on the top line. the entire screen scrolls down). <BACKSPACE) may be installed to have the same effect. A word is defined as a sequence of characters delimited by one of the following characters: Ispacel <) ..e. * Word right Ctrl-F Moves the cursor to the beginning of the word to the right.e. Scroll up Ctrl-W Scrolls 'up' towards the beginning of the file. the screen scrolls up one line. Word left Ctrl-A Moves the cursor to the beginning of the word to the left. i. Line up Ctrl-E Moves the cursor to the line above. If the cursor is on the second-last line. USING THE TURBO SYSTEM 23 . This command does not work across line breaks. Line down Ctrl-X Moves the cursor to the line below. See the definition of a word above. where it stops. Character right Ctrl-D Moves the cursor one character to the right non-destructively. This command works across line breaks. when the cursor reaches the left edge of the screen.8. when the cursor reaches the right end of the screen. This command works across line breaks.e. without affecting the character there.()[ ] + _/$. in column 128. A . the text starts scrolling horizontally until the cursor reaches the extreme right of the line.e. The cursor remains on its line until it reaches the bottom of the screen. i. one line at a time (i.5.1 Character left Ctrl-S Moves the cursor one character to the left non-destructively.Basic Movement Commands 1. the screen scrolls down one line. This command does not work across line breaks. i. without affecting the character there.e. i.. it stops.

the cursor moves one screenful less one line backwards in the text. and. X. The cursor remains on its line until it reaches the top of the screen. Ctrl-O Ctrl-S moves the cursor to the extreme left of the line. and to the last cursor position.1 Basic Movement Commands Scroll down Ctrl-Z Scrolls 'down' towards the end of the file.5.B. Page down Ctrl-C Moves the cursor one page down with an overlap of one line. Once you master them. Ctrl-Q Ctrl-C moves it all the way 'down' to the end of the file. 24 TURBO Pascal Language Manual .8. and C. the cursor moves one screenful less one line forwards in the text. Ctrl-Q Ctrl-E moves the cursor to the top of the screen. i.e.e. you will probably sometimes want to move more rapidly. They repeat the pattern from before: E R S D X C i. Ctrl-Q Ctrl-D moves it to the extreme right of the line. These commands require two characters to be entered: first a Ctrl-Q and then one of the following control characters: S. Page up Ctrl-R Moves the cursor one page up with an overlap of one line.e.1. 1. Ctrl-O Ctrl-R moves the cursor all the way 'up' to the start of the file. D. and they are easy to learn and understand. E. to the beginning and end of the text. Try to use them all for a while and see how natural they feel. The TURBO editor provides five commands to move rapidly to the extreme ends of lines. the entire screen scrolls up).5.e. R. Ctrl-Q Ctrl-X moves it to the bottom of the screen. i. one line at a time (i.2 Extended Movement Commands The commands discussed above will let you move freely around in your program text.

2 To left on line Ctrl-Q Ctrl-S Moves the cursor all the way to the left edge of the screen. The command works even if the block is not displayed (see hide /display block later).8.e. To end of block Ctrl-Q Ctrl-K Moves the cursor to the position of the block end marker set with Ctrl-K CtrlK (hence the K). The command works even if the block is not displayed (see hide/display block later).Extended Movement Commands 1.5. i. To top of screen Moves the cursor to the top of the screen. To right on line Ctrl-Q Ctrl-D Moves the cursor to the end of the line. To bottom of screen Moves the cursor to the bottom of the screen. i. USING THE TURBO SYSTEM 25 . to the position following the last printable character on the line. Trailing blanks are always removed from all lines to preserve space. Finally the Ctrl-Q prefix with a B. or the block end marker is not set. to column one.e. To end of file Moves to the last character of the text. or P control character allows you to jump far within the file: To beginning of block Ctrl-Q Ctrl-B Ctrl-Q Ctrl-C Ctrl-Q Ctrl-R Ctrl-Q Ctrl-X Ctrl-Q Ctrl-E Moves the cursor to the the position of the block begin marker set with Ctrl-K Ctrl-B (hence the B). To top of file Moves to the first character of the text. K. or the block begin marker is not set.

and lines. words.1. They can be divided into three groups: one command which controls the text entry mode (insert or overwrite). and one extended command. You switch between these modes with the insert mode on/off command CtrlV.8. This command is particularly useful to move back to the last position after a S ave operation or after a find or find/replace operation. This command (Ctrl-Q Ctrl-L) is described in section 1. Characters entered then replace existing characters under the cursor.5. Overwrite mode may be chosen if you wish to replace old text with new text. The existing text to the right of the cursor simply moves to the right while you enter the new text. 1. Insert mode is the default value when the editor is invoked. 1.2 Extended Movement Commands To last cursor position Ctrl-Q Ctrl-P Moves to the last position of the cursor (the P being a mnemonic for Position). and it lets you insert new text into an existing text. Notice that the TURBO editor provides a 'regret' facility which lets you 'undo' changes as long as you have not left the line. and the current mode is displayed in the status line at the top of the screen. 26 TURBO Pascal Language Manual . you may choose between two entry modes: Insert and Overwrite.8 . a number of simple commands.6 Insert and Delete Commands These commands let you insert and delete characters.6.B.B.8.1 Insert or Overwrite? Ctrl-V I nsert mode on/off When you enter text.

6. This command does not work across line breaks. Delete right word Ctrl-T * Deletes the word to the right of the cursor. ( ) [ ] + . The (BACKSPACE) key which normally backspaces non-destructively like Ctrl-S may be installed to perform this function if it is more conveniently located on your keyboard. This command works across line breaks.3 Extended Delete Command One extended delete command is provided: a command to quickly erase from the cursor position to the end of the line. No provision exists to restore a deleted line. i. This command works across line breaks. Delete character under cursor Ctrl-G Deletes the character under the cursor and moves any characters to the right of the cursor one position to the left.8. A • Insert line Ctrl-N Inserts a line break at the cursor position.e. so take care! 1.6.e. The cursor moves to the left edge of the screen.2 Simple Insert/Delete Commands Delete left character (DELETE) Moves one character to the left and deletes the character there. (RUBOUT). or if your keyboard lacks a (DELETE) key (sometimes labeled (DEL). A word is defined as a sequence of characters delimited by one of the following characters: Ispacel ( ) . .2 1. USING THE TURBO SYSTEM 27 . The cursor does not move. i.Simple Insert IDelete Commands 1. it may be used to remove line breaks.6. Any characters to the right of the cursor move one position to the left. Delete line Ctrl-Y Deletes the line containing the cursor and moves any lines below one line up.I $.8. or (RUB»). . you can use it to remove line breaks.8.

and written to a file. and a special command conveniently marks a single word as a block. the block may be copied. we'll go on and discuss the use of blocks.1. A command is available to read an external file into the text as a block. two characters each in the standard command definition)' and you may ignore them at first if you feel a bit dazzled at this point. .8. and the block only becomes visibly marked when the End block marker is set. As above. moved. Later on. Mark single word Ctrl-K Ctrl-T This command marks a single word as a block. it is internally marked and may be manipulated. from a single character to several pages of text. For the persevering. A block of text is simply any amount of text. A block is marked by placing a Begin block marker at the first character and an End block marker at the last character of the desired portion of the text. or copy whole chunks of text. But even if the block is not visibly marked. you should return to this section. M ark block end Ctrl-K Ctrl-K This command marks the end of a block. and the block only becomes visibly marked when the Begin block marker is also set. then this word will be marked. () [ r ' + .. delete.3 Extended Delete Command Delete to end of line Ctrl-Q Ctrl-Y Deletes all text from the cursor position to the end of the line. the marker itself is not visible on the screen. A word is defined as a sequence of characters delimited by one of the following characters: Ispacel <) . if not then the word to the left of the cursor will be marked. * 28 TURBO Pascal Language Manual . 1. Thus marked.End block sequence which is a bit clumsy when marking just one word. The marker itself is not visible on the screen. and thus replaces the Begin block .7 Block Commands All block commands are extended commands (Le. and then only if the screen is installed to show some sort of highlighting.8. when you feel the need to move.6. If the cursor is placed within a word. Mark block begin Ctrl-K Ctrl-B This command marks the beginning of a block. deleted./$.

The block disappears from its original position and the markers remain around the block at its new position. and no error message is issued. Delete block Ctrl-K Ctrl-Y This command deletes the previously marked block. When this command is issued. If no block is marked.8. exactly as if it was a block that was moved or copied. delete. No provision exists to restore a deleted block. Block related cursor movements (jump to beginning/end of block) work whether the block is hidden or displayed. The file specified may be any legal filename. .Block Commands 1. you are prompted for the name of the file to read. USING THE TURBO SYSTEM 29 . The block read in is marked as a block. Move block Ctrl-K Ctrl-V This command moves a previously marked block from its original position to the cursor position. and write to a file) work only when the block is displayed. the command performs no operation.PAS is automatically assumed: A file without type is specified as a name followed by a period. and the markers are placed around the new copy of the block. The original block is left unchanged. Block manipulation commands (copy. Copy block Ctrl-K Ctrl-C This command places a copy of a previously marked block starting at the cursor position. If no file type is specified.7 H ide/display block Ctrl-K Ctrl-H This command causes the visual marking of a block (dim text) to be alternately switched off and on. move. If no block is marked. the command performs no operation. so take care! Read block from disk Ctrl-K Ctrl-R This command is used to read a file into the current text at the cursor position. and no error message is issued.

g. especially when you return to make changes after some time.CMD. If no file type is specified. and no error message is issued. and any associated disk file is not affected.PAS is automatically assumed.B Miscellaneous Editing Commands This section collects a number of commands which do not logically fall into any of the above categories. as they are used for special purposes by the TURBO system. Remember that Pascal allows you to write extremely beautiful source texts -do it. Saving the edited file on disk is done explicitly with the Save command from the main menu or automatically in connection with a compilation or definition of a new Work file. and . especially this first one: End edit Ctrl-K Ctrl-D This command ends the edit and returns to the main menu. .BAK.CHN.B.8. tab positions are automatically set to the beginning of each word on the line immediately above the cursor. Avoid the use offile types . The editing has been performed entirely in memory. variable declarations and such. but more importantly to keep the program easy to understand.COM/. you are prompted for the name of the file to write to. Tab Ctrl-I There are no fixed tab positions in the TURBO editor.1. the command performs no operation. A file without type is specified as a name followed by a period. 1. . This provides a very convenient automatic tabbing feature especially useful in program editing where you often want to line up columns of related items. e. 30 TURBO Pascal Language Manual . Instead. not for the sake of the purists.7 Block Commands Write block to disk Ctrl-K Ctrl-W This command is used to write a previously marked block to a file. The block is left unchanged. They are nonetheless important. and the markers remain in place. a warning is issued before the existing file is overwritten. If no block is marked. When this command is issued.The file specified may be any legal filename. If the file specified already exists.

Notice that Ctrl-A has a special meaning: it matches any character and may be used as a wildcard in search strings. then A. Some days you'll find yourself continuously falling asleep on the Ctrl-Y key. the cursor does not return to column one but to the starting column of the line you just terminated. the indentation of the current line is repeated on each following line. Search strings may be edited with the Character Left. the Delete line (Ctrl-Yl command can regrettably only be regretted. Word Right recalls the previous search string which may then be edited. You may thus include a line break in a search string by specifying Ctrl-M Ctrl-J.g.Miscellaneous Editing Commands 1. Character Right.8 Auto tab on/off Ctrl-Q Ctrl-I The auto tab feature provides automatic indentation. The following options are available: USING THE TURBO SYSTEM 31 . also control characters. For this reason. The search string may contain any characters. Enter the string you are looking for and terminate with <RETURN). When the search string is specified. When auto tab is active. and you are prompted for a search string. When you want to change the indentation.8. The search operation may be aborted with the Abort command (Ctrl-U). Control characters are entered into the search string with the Ctrl-P prefix: enter e.e. Restore line Ctrl-Q Ctrl-L This command lets you regret changes made to a line as long as you have not left the line. A good long break usually helps. The line is simply restored to its original contents regardless of what changes you have made. Find Ctrl-Q Ctrl-F The Find command lets you search for any string of up to 30 characters. a Ctrl-A by holding down the Control key while pressing first P. the status line is cleared. you are asked for search options. the minute you leave it. changes are there to stay. When you enter this command. Word Left. the message Indent is displayed in the status line. But only as long as you remain on the line. and Word Right commands. When active. i. with vast consequences. use any of the cursor right or left commands to select the new column. when you hit <RETURN). and when passive the message is removed. Auto tab is active by default. not restored.

Find the n'th occurrence of the search string. 'Block' will match both 'blockhead' and 'BLOCKADE'. etc. Search strings may be edited with the Character Left. i. If the text contains a target matching the search string. 32 TURBO Pascal Language Manual . When you enter this command.e. the status line is cleared. the word 'terminal'. Enter the string you are looking for and terminate with <RETURN). and you are prompted for a search string. i. The search operation may be repeated by the Repeat last find command (Ctrl-L). Notice that Ctrl-A has a special meaning: it matches any character and may be used as a wildcard in search strings.8 Miscellaneous Editing Commands B G n u w Examples: Search backwards. i.e. i. the cursor is positioned at the end of the target.e. Word Left. Find and replace Ctrl-Q Ctrl-A The Find and Replace command lets you search for any string of up to 30 characters and replace it with any other string of up to 30 characters. Character Right.1. search the entire text.g. Ignore upper/lower case. irrespective of the current cursor position. You may thus include a line break in a search string by specifying Ctrl-M Ctrl-J. then A. Terminate the list of options (if any) with <RETURN). The search string may contain any characters.e. Find the 125th occurrence of the search string. Word Right recalls the previous search string which may then be edited. search backwards and ignore upper/lower case. the search string 'term' will only match the word 'term'. W BU 125 search for whole words only. Search for whole words only. skip matching petterns which are embedded in other words. search from the current cursor position towards the beginning of the text.g. The search operation may be aborted with the Abort command (Ctrl-U). also control characters. and the search starts.e. i.e. a Ctrl-A by holding down the Control key while pressing first P. Control characters are entered into the search string with the Ctrl-P prefix: enter e. and Word Right commands. n = any number. Global search.8. not e. counted from the current cursor position. i. regard upper and lower case alphabeticals as equal.

Miscellaneous Editing Commands 1. Find and replace n occurrences of the search string. The search and replace options are: B Search and replace backwards. The search and replace operation may be repeated by the Repeat last find command (Ctrl-L). Repeat last find Ctrl-L This command repeats the latest Find or Find and replace operation exactly as if all information had been re-entered. Depending on the options specified. control character entry and editing is performed as above. i. G n N u w Examples: N10 GWU Find the next ten occurrences of the search string and replace without asking. Finally you are prompted for options. deleted. i. the target will be replaced with nothing. and you are asked the question: Replace (YIN)? on the prompt line at the top of the screen. Replace without asking.8. i.e.e. You may abort the search and replace operation at this point with the Abort command (CtrlU). If you just press <RETURN>. search and replace from the current cursor position towards the beginning of the text. USING THE TURBO SYSTEM 33 . Enter up to 30 caharcters. Ignore upper/lower case. i. skip matching petterns which are embedded in other words. i. counted from the current cursor position. Global search and replace. and the search and replace starts. the string may be found. n = any number. irrespective of the current cursor position. regard upper and lower case alphabeticals as equal. but Ctrl-A has no special meaning in the replace string. you are asked to enter the string to replace the search string. When found (and if the N option is not specified).e. the cursor is positioned at the end of the target. search and replace in the entire text.e. Search and replace whole words only. do not stop and ask Replace (Y/N) for each occruurence of the search string. Terminate the list of options (if any) with <RETURN>. Ignore upper/lower case.8 When the search string is specified.e.e. Find and replace whole words in the entire text. i.

9.g. 1. 1. all trailing blanks are automaticaly deleted. want to enter a Ctrl-G into a text string to ring the bell. when matching indented begin . These differencies are discussed in this section. 1. E. or during entry of a search string or a file name (block Read and Write). This way of moving the cursor is especially useful e. This does not mean that the screen is full of blanks.1 Cursor Movement The cursor movement controls Ctrl-S. Ctrl-S and Ctrl-D do not work across line breaks. it has been necessary to include some commands not found in WordStar. To move from one line to another you must use Ctrl-E. or Ctrl-F. Ctrl-X.8. Ctrl-A. 0. Control characters are displayed as low-lighted (or inverse. If you e.8 Miscellaneous Editing Commands Control character prefix Ctrl-P The TURBO editor allows you to enter control characters into the file by prefixing the desired control character with a Ctrl-P.g. Abort operation Ctrl-U The Ctrl-U command lets you abort any command in process whenever it pauses for input.1. on the contrary.end pairs. or what have you) capital letters. and X move freely around on the screen and do not jump to column one on empty lines. WordStar Someone used to WordStar will notice that a few TURBO commands work slightly different.2 Mark Single Word Ctrl-K Ctrl-T is used to mark a single word as a block which is more convenient than the two-step process of marking the beginning and the end of the word separately. you must first press Ctrl-P and then Ctrl-G. and although TURBO naturally only contains a subset of WordStar's commands. 34 TURBO Pascal Language Manual . like when Search and Replace asks Replace YIN?.9.9 The TURBO editor vs.

As editing in TURBO is done entirely in memory. 1.9.9.9.9. tabs are automatically set to the start of each word on the line immediately above the cursor. 1. Instead.5 Tabulator No fixed tab settings are provided.6 Auto Indentation The Ctrl-Q Ctrl-I command switches the auto indentation feature on and off. TURBO's Ctrl-K Ctrl-D does not resemble WordStar's Ctrl-K Ctrl-Q (quit edit) command either. it is left in memory ready to be Compiled or Saved. This must be done explicitly with the Save command from the main menu or automatically in connection with a compilation or definition of a new Work file. 1. USING THE TURBO SYSTEM 35 .3 End Edit The Ctrl-K Ctrl-D command has a different effect than in WordStar.End Edit 1.9.3 1.4 Line Restore The Ctrl-Q Ctrl-L command restores a line to its contents before edit as long as the cursor has not left the line. as the changed text is not abandoned. this command does not change the file on disk.

6 Auto Indentation Notes: 36 TURBO Pascal Language Manual .1.9.

a to z. The asterisks indicate reserved words not defined in standard Pascal. reserved words are written in boldface. and_ (underscore) Digits: 8 1 2 3 4 5 6 7 8 9 Special s·.. and special symbols: Letters: A toZ. digits.BASIC LANGUAGE ELEMENTS 2 2. BASIC LANGUAGE ELEMENTS 37 . Brackets: (.) may be used instead of [ and] Comments: (* and *) may be used instead of { and} 2.2 Reserved Words Reserved words are integral parts of TURBO Pascal and cannot be redefined.mbols: + ~ < > ( ) []{}.. The reserved words are: "* absolute and "* array begin case const div do dOlJIlto else end "* external file for forward function goto if in inline label mod "* nil not of or packed procedure program record repeat set shl "* "* "* shr string then to type until var "hi Ie with xor Throughout this manual.1 Basic Symbols The basic vocabuiary of TURBO Pascal consists of basic symbols divided into letters. Reserved words must thus never be used as user defined identifiers. and. BASIC LANGUAGE ELEMENTS 2. Certain operators and delimiters are formed using two special symbols: Assignment operator: : = Relational operators:< > <= >= Subrange delimiter: . */ 'u$ No distinction is made between upper and lower case letters.

Throughout this manual. variables.2. The following standard identifiers are therefore best left to their special purposes: ArcTan Assign Aux AuxlnPtr AuxOutPtr BlockRead BlockWri te Boolean BufLen Byte Chain Char Chr Close C I rIDL C 1rScr Con ConInPtr ConOutPtr Concat ConstPtr Copy Cos CrtExi t Crtlnit DelLine Delay Delete IDF IDIN Erase Execute Exp False Fi lePos FileSize Fi llChar Flush Frac GetMem Got oX'! HeapPtr Hi IOresul t Input InsLine Insert Int Integer Kbd KeyPressed Length Ln Lo LowVideo Lst LstOutPtr Mark Maxlnt Mem MemAvai I Move New NormVideo Odd Ord Output Pi Port Pos Pred Ptr Random Randomize Read Read In Real Release Rename Reset Rewri te Round Seek Sin SizeOf Sqr Sqrt Str Succ Swap Text Trm True Trunc UpCase Usr UsrlnPtr UsrOutPtr Val Wri te Wri teln Each TURBO Pascal implementation further contains a number of dedicated standard identifiers which are listed in appendices A and B . and functions.3 Standard Identifiers 2.1 ). are written in a combination of upper and lower case letters. standard identifiers. In the text (as opposed to program examples). procedures.3 Standard Identifiers TURBO Pascal defines a number standard identifiers of predefined types. 38 TURBO Pascal Language Manual . constants. Any of these identifiers may be redefined but it will mean the loss of the facility offered by that particular identifier and may lead to confusion. they are furthermore printed in italics. like all other identifiers (see section 4.

but source code prepared with other editors may use longer lines. any character beyond the 127th is ignored by the compiler.Delimiters 2. For this reason the TURBO editor allows only 127 characters on a line. and a warning is issued.4 Delimiters Language elements must be separated by at least one of the following delimiters: a blank.4 2. BASIC LANGUAGE ELEMENTS 39 . If such a text is read into the TURBO editor. line breaks will be automatically inserted. or a comment.5 Program lines The maximum length of a program line is 127 characters. 2. an end of line.

2.5 Notes: Program lines 40 TURBO Pascal Language Manual .

as the multiplication causes an overflow. the expression 1000 100 / 50 will not yield 2000. A variable of type Byte occupies one byte in memory. in TURBO Pascal limited to a range of -32768 through 32767.1 Integer Integers are whole numbers. of the range 0 . char. Integers occupy two bytes in memory.. 3.2 Byte The type Byte is a subrange of the type Integer.e. an Integer value may be specified instead and vice versa. STAN IOAIRtD SCAILAIfl TYPES A data type defines the set of values a variable may assume. boolean. whenever a Byte value is expected. 255. Bytes are therefore compatible with integers. Bytes and Integers may be mixed in expressions and Byte variables may be assigned integer values. * 3. Notice in particular that partial results in integer expressions must be kept within the integer range. Although data types in TURBO Pascal can be quite sophisticated. Overflow of integer arithmetic operations is not detected. i. or be one of the standard scalar types: integer. For instance. A simple type may either be defined by the programmer (it is then called a declared scalar type). STANDARD SCALAR TYPES 41 .STANDARD SCALAR TYPES 3 3. Every variable in a program must be associated with one and only one data type. real. or byte. The following is a description of these five standard scalar types. they are all built from simple {unstructured) types. Furthermore.

Reals cannot be used in controlling for and case statements. These are defined such that False < True. 2) 3) 4) 5) Reals cannot be used in array indexing. Reals occupy 6 bytes in memory. 'A' < 'S'. Subranges of reals are not allowed. A Boolean variable occupies one byte in memory.3. 3.4 Boolean A boolean value can assume either of the logical truth values denoted by the standard identifiers True and False. A Char variable occupies one byte in memory. Overflow during an arithmetic operation involving reals causes the program to halt. displaying an execution error. 3.3 Real The range of real numbers is 1E-38 through 1E+38 with a mantissa of up to 11 significant digits. Characters are ordered according to their ASCII value. the following differences between reals and other scalar types should be noticed: 1) The functions Pred and Succ cannot take real arguments. The ordinal (ASCII) values of characters range from 0 to 255.5 Char A Char value is one character in the ASCII character set. Reals cannot be used to define the base type of a set. e.g. 42 TURBO Pascal Language Manual . An underflow will cause a result of zero.3 Real 3. Although the type real is included as a standard scalar type.

An identifier consists of a letter or underscore followed by any combination of letters. constants. It is nevertheless encouraged as it leads to more legible identifiers. G is not a legal hexadecimal digit illegal as an integer. USER DEFINED LANGUAGE ELEMENTS 4. starts with a digit illegal. An identifier is limited in length only by the line length of 127 characters. types. must not contain a space As TURBO Pascal does not distinguish between upper and lower case letters. variables. procedures. Integer constants are whole numbers expressed in either decimal or hexadecimal notation.2345 illegal. Examples: TURBO square personLcounted BirthDate 3rdRoot Two Words illegal. This mixed mode will be used for all identifiers throughout this manual. Hexadecimal constants are identified by being preceeded by a doliar-sign:$ABC is a hexadecimal constant. and functions.2 Numbers Numbers are constants of integer type or of real type.USER DEFINED LANGUAGE ELEMENTS 4 4.1 Identifiers Identifiers are used to denote labels. The decimal integer range is -32768 through 32767 and the hexadecimal integer range is$OOOO through$FFFF. digits. or underscores. Examples: 1 12345 -1 $123 $ABC $123G 1. VeryLongldentifier is easier to read for the human reader than VERYLONGIDENTlFIER. contains a decimal part USER DEFINED LANGUAGE ELEMENTS 43 . the use of mixed upper and lower case as in BirthDate has no functional meaning. 4. and all characters are significant.

. it is an integer 4. Separators are not allowed within numbers.5678 -0. A string is compatible with an array of Char of the same length. with the letter E preceding the scale factor meaning "times ten to the power ot". Exponential notation may be used. i. Examples: 1. . The four consecutive single quotes in example 3 thus constitute a string containing one quote.012 1E6 2E-5 -1..0 1234.e. An integer constant is allowed anywhere a real constant is allowed. As shown in example 2 and 3. All string constants are compatible with all string types. Examples: 'TURBO' 'You' '11 see' . but it is not a real.4. Strings containing only a single character are of the standard type char.the quotes enclosing no characters. a single quote within a string is written as two consecutive quotes. 44 TURBO Pascal Language Manual .3 Strings A string constant is a sequence of characters enclosed in single quotes. denoting the empty string .: 'This is a string constant ' A single quote may be contained in a string by writing two successive single quotes.2 Numbers The range of Real numbers is 1E-38 through 1 E+38 with a mantissa of up to 11 significant digits.is compatible only with string types. 2345678901E+12 1 legal. The last example .

3. Control-G (Bell). Notice that lower case is treated as upper case. It is delimited by the curly braces { and}. Control-[ (Escape). respectively. Control characters may also be mixed with text strings: 'Waiting for input! '~G~G~G' Please wake up' tt27'U ' 'This is another line of text ' ~M~J These three strings contain 37. Two notations for control characters are supported: 1) The tt symbol followed by an integer constant in the range 0 . denotes the corresponding control character. 255 denotes a character of the corresponding ASCII value.1 4.1 Control Characters TURBO Pascal also allows control characters to be embedded in strings.3. which may be replaced by the symbols (* and *). Control-L (Form Feed).4 Comments A comment may be inserted anywhere in the program where a delimiter is legal. ASCII 1B hex (Escape). and 31 characters. and 2) the ~ symbol followed by a character. Examples: {ThiS is a comment} (* and so is this *) USER DEFINED LANGUAGE ELEMENTS 45 . 3.Control Characters 4. and four characters. 4. Examples: u10 u$lB ~G ~ 1 [ ~ ASCII 10 dec imal (Line Feed).. respectively. Sequences of control characters may be concatenated into strings by writing them without separators between the individual characters:: u13u10 u27~Uu20 ~G~G~G~G The above strings contain two. three.

..4. and a summary of compiler directives is located in appendix E .5 Compiler Directi.B+.. F1L} {$R. The syntax of the directive or directive list depends upon the directive(s) selected.V-} (*$X-*) Notice that no spaces are allowed before or after the dollar-sign. Examples: {$1 . *). even if they contain comments.es A number of features of the TURBO Pascal compiler are controlled through compiler directives. 46 TURBO Pascal Language Manual . and C* .:.4 Comments Curly braces may not be nested within curly braces. curly braces may nested withinC * . A compiler directive consists of an opening brace immediately followed by a dollar-sign immediately followed by one compiler directive letter or a list of compiler directive letters separated by commas. A compiler directive is introduced as a comment with a special syntax which means that whenever a comment is allowed in a program. However. A full description of each of the compiler directives follow in the relevant sections.. 4. thus allowing entire sections of source code to be commented away. a compiler directive is also allowed. *) may not be nested within C* . *) and vise versa.} {$1 INCLUDE.

2 Declaration Part The declaration part of a block declares all identifiers to be used within the statement part of that block (and possibly other blocks within it). program Accountant (Input. the program heading is purely optional and of no significance to the program. The declaration part is divided into five different sections: 1) 2) 3) 4) 5) Label declaration part Constant definition part Type definition part Variable declaration part Procedure and function declaration part Whereas standard Pascal specifies that each section may only occur zero or one time. Output).PROGRAM HEADING AND PROGRAM BLOCK 5 S. and only in the above order. and a statement part. PROGRAM HEADING AND PROGRAM BLOCK 47 . Printer). S. and optionally lists the parameters through which the program communicates with the environment. The list consists of a sequence of identifiers enclosed in parentheses and separated by commas. in which all objects local to the program are defined. TURBO Pascal allows each of these sections to occur any number of times in any order in the declaration part. it gives the program a name. If present. program Wri ter( Input. Each is described in detail in the following. The program block is further divided into a declaration part. which specifies the actions to be executed upon these objects.1 Program Heading In TURBO Pascal. Examples: program C i rc 1e s. S. PROGRAM HEADING AND PROGRAM BLOCK A Pascal program consists of a program heading followed by a program block.

2.2 Constant Definition Part The constant definition part introduces identifiers as synonyms for constant values.1 Label Declaration Part 5. 5. TURBO Pascal allows both numbers and identifiers to be used as labels. Whereas standard Pascal limits labels to numbers of no more than 4 digits.2. Constants are either strings or numbers as defined in sections 4. PassWord 'SFSAM' . CursHome = ~ [ 'V'. Boolean (the truth value true). error. 48 TURBO Pascal Language Manual . Example: label 10. Before use. Boolean (the truth value false).2. they may be referenced without previous definition: Name: Type and value: Pi False True Maxint Real (3. and it is followed by a list of label identifiers separated by commas and terminated by a semicolon.5. enabling direct branching to that statement by a goto statement. the label must be declared in a label declaration part. i. Max = 1024. Example: canst Limi t = 255. Each constant assignment consists of an identifier followed by an equal sign and a constant. a constant definition part may also define typed constants. As described in section 13.3. Integer (32767). The reserved word const heads the constant definition part.1415926536E+OO).2 and 4. The reserved word label heads this part. A label consists of a label name followed by a colon.1 Label Declaration Part Any statement in a program may be prefixed with a label. The following constants are predefined in TURBO Pascal.e. Quit. 999. and is followed by a list of constant assignments separated by semi-colons.

and the programmer may create his own types through the use of the type definition. A variable declaration consists of the reserved word var followed by one or more identifier(s). each followed by a colon and a type. Several standard type identifiers are provided. X.tues. 127] of Byte. List = array[ 1. Day = (mon. The declaration must textually precede any use of the variable. I.fri.2.2.3 Type Definition Part A data type in Pascal may be either directly described in the variable declaration part or referenced by a type identifier.thur. PROGRAM HEADING AND PROGRAM BLOCK 49 . however.sun). 5. separated by commas.10] of Real. The 'scope' of this identifier is the block in which it is defined. Y: Integer. that any such block within another block may define another variable using the same identifier. Example: type Number = Integer. This creates a new variable of the specified type and associates it with the specified identifier. J. The reserved word type heads the type definition part. Each type assignment consists of a. i.. Accepted. This variable is said to be local to the block in which it is declared (and any blocks within that block).2.wed. type identifier followed by an equal sign and a type. Buffer: arr~[0 . . and any block within that block. and the variable declared on the outer level (the global variable) becomes inaccessible. SubTotal: Real. Period: Day. Example: var Resul t.e.Type Definition Part 5.3 5. More examples of type definitions are found in subsequent sections. and it is followed by one or more type assignments separated by semicolons. Intermediate.sat. the variable must be 'known' to the compiler before it can be used.4 Variable Declaration Part Every variable occurring in a program must be declared before use. Note. Val id: Boolean.

A function is activated when its designator is met as part of an expression (see section 6. program execution continues with the statement immediately following the calling statement.2.1.2). A function declaration serves to define a program part which computes and returns a value (see section 16. The statement part takes the form of a compound statement followed by a period or a semi-colon.2.2). It specifies the actions to be executed by the program. A procedure is activated from a procedure statement (see section 7.5.3). 5.3 Statement Part The statement part is the last part of a block. 50 TURBO Pascal Language Manual . and upon completion.5 Procedure and Function Declaration Part 5. A compound statement consists of the reserved word begin.2).5 Procedure and Function Declaration Part A procedure declaration serves to define a procedure within the current procedure or program (see section 16. followed by a list of statements separated by semicolons. terminated by the reserved word end.

i. 9.1. <. EXPRESSIONS 51 . variables. =. =. and in. String types. constants.1 Operators Operators fall into five categories. and 12. 6. < > Sequences of operators of the same precendece are evaluated from left to right. and xor. Multiplying operators:~. Real.EXPRESSIONS 6 6. This section describes how to form expressions from the standard scalar types Integer. then the result is also of type Real.1. Expressions containing declared scalar types. >. diy. denoted by their order of precedence: 1) 2) 3) 4) 5) Unary minus (minus with one operand only). Not operator. and Char. EXPRESSDONS Expressions are algorithmic constructs specifying rules for the computation of values. Expressions within parentheses are evaluated first and independently of preceding or succeeding operators. mod. Relational operators: =. and function designators. and Set types are described in sections 8. then the result is of type Integer. I. 6.2 . Adding operators: +. Boolean. If both of the operands of the mUltiplying and adding operators are of type Integer.e. and shr. They consist of operands. or. and.1 Unary Minus The unary minus denotes a negation of its operand which may be of Real or Integer types. <>. If one (or both) of the operands is of type Real. combined by means of operators as defined in the following. shl. -.2 . respectively.

75 = 30 =2 = False =4 2 shl 7 256 shr 7 =2 = 256 52 TURBO Pascal Language Manual .1.6. Integer Real.2 Not Operator 6.3 Multiplying Operators Type of operands Type of resul t Operator Operation * * * / / / div mod and and shl shr Examples: rnul t ipl icat ion rnul t ipl icat ion rnul t ipl icat ion division division division Integer division modulus ari thmet ic and logical and shift left shift right Real Integer Real.1.1.2 Not Operator The not operator negates (inverses) the logical value of its Boolean operand: not True not False = False = True TURBO Pascal also allows the not operator to be applied to an Integer operand. Examples: not 0 not -15 = -1 = 14 =$DCBA not $2345 6. in which case bitwise negation takes place. Integer Integer Real Integer Integer Integer Boolean Integer Integer Real Integer Real Real Real Real Integer Integer Integer Boolean Integer Integer 12 34 123 / 4 123 div 4 12 mod 5 True and False 12 and 22 * = 408 = 30.

is greater than b. EXPRESSIONS 53 .e. True or False. is less than or equal to b. Real.Adding Operators 6. is not equal to b. is greater than or equal to b. Char.1. Operands of type Integer. The type of the result is always Boolean. equal to not equal to greater than less than greater than or equal to less than or equal to <> > < >= <= Examples: a = b a <> b a > b a < b a >= b a <= b true true true true true true if a if a if a if a if a if a is equal to b. i. Integer. Integer Real Integer Real.5 Relational Operators The relational operators work on all standard scalar types: Real. is less than b. and Byte. <:) True or False 12 or 22 True xor False 12 xor 22 = 579 = True = True = 26 = 30 = 333.4 Adding Operators Operation addition addition addition subtraction subtraction subtraction arithmetic or logical or arithmetic xor logical xor Type of operands Type of result Operator + + + or or xor xor Examples: Real Integer Real. Integer Integer Boolean Integer Boolean Real Integer Real Real Integer Real Integer Boolean Integer Boolean 123+456 456-123.1. Boolean.0 6.1.4 6. and Byte may be mixed.

If the function is not one of the pre-defined standard functions. Examples: Round(PlotPos) Write In(Pi * (Sqr(R))) (Max(X.2 F unction Designators A function designator is a function identifier optionally followed by a parameter list. which is one or more variables or expressions separated by commas and enclosed in parentheses. The occurrence of a function designator causes the function with that name to be activated.Height) 54 TURBO Pascal Language Manual .6.Y) < 25) and (Z > Sqrt(X * y)) Volume(Radius. it must be declared before activation.2 Function Designators 6.

7. statements are separated by semi-colons. It is used to specify that a certain value is to be assigned to a certain variable. and empty statement. : = 4 "* Pi "* R "* R. 7. These are the assignment statement. Assignment is possible to variables of any type (except files) as long as the variable (or the function) and the expression are of the same type.Angle "* Pi. the type of the expression may be Inte- ger. if the variable is of type Real. procedure statement. As an exception.STATEMENTS 7 7.1.1 Assignment Statement The most fundamental of all statements is the assignment statement. An assignment consists of a variable identifier followed by the assignment operator : = followed by an expression. Statements may be either simple or structured. each specifying one part of the action. STATEMENTS 55 . : = False. Examples: .1 Simple Statements Simple statements are statements which contain no other statements. never simultaneously. goto statement.Angle := AccessOK Ent ry : = SpherVol . The statement part is enclosed by the reserved words begin and end and within it. In this sense Pascal is a sequential programming language: statements are executed sequentially in time. Answer = PassWord. S1rATIEM IE ruTS The statement part defines the action to be carried out by the program (or subprogram) as a sequence of statements.

Sort(Address) . Examples: Find(Name. control is transferred to the named procedure. When the procedure statement is encountered during program execution. labels must be declared. and which has no effect.1. It is thus not possible to jump into or out of procedures and functions. The following rules should be observed when using goto statements: 1) Before use.1.2 Procedure Statement A procedure statement serves to activate a previously defined user-defined procedure or a pre-defined standard procedure. 7. UpdateCustFi le(CustRecord). 2) The scope of a label is the block in which it is declared. When the procedure finishes. program execution continues from the statement following the procedure statement.Address). 7.3 Goto Statement A goto statement consists of the reserved word goto followed by a label identifier. while Answer <> " do. which is a list of variables or expressions separated by commas and enclosed in parentheses.1. The statement consists of a procedure identifier. optionally followed by a parameter list. and the value of possible parameters are transferred to the procedure. It serves to transfer further processing to that point in the program text which is marked by the label. Examples: begin end. repeat until KeyPressed. {wait for any key to be hit} 56 TURBO Pascal Language Manual . The declaration takes place in a label declaration in the declaration part of the block in which the label is used.4 Empty Statement An 'empty' statement is a statement which consists of no symbols.1.2 Procedure Statement 7. It may occur whenever the syntax of Pascal requires a statement but no action is to take place.7. Uppe rCas e ( Text) .

7. conditionally (conditional statements)' or repeatedly (repetitive statements). Small := Big.2. If it is false.2 7.2.2.2. The discussion of the with statement is deferred to section 11.2 Conditional Statements A conditional statement selects for execution a single one of its component statements. Notice that else must not be preceded by a semi-colon.1 Compound Statement A compound statement is used if more than one statement is to be executed in a situation where the Pascal syntax aIJows only one statement to be specified. 7.1 If Statement The if statement specifies that a statement be executed only if a certain condition (Boolean expression) is true. STATEMENTS 57 . 7. Big := Tmp. end.2. Example: if Small> Big then begin Tmp : = Small.2 Structured Statements Structured statements are constructs composed of other statements which are to be executed in sequence (compound statements). and specifies that the component statements are to be executed in the sequence in which they are written. then either no statement or the statement folJowing the reserved word else is to be executed.Structured Statements 7. It consists of any number of statements separated by semi-colons and enclosed within the reserved words begin and end.

then either no statement is executed..7.2.). optionally.2. 58 TURBO Pascal Language Manual .. end.2. the else-clause part belongs generally to the last if statement which has no else part. 7.2. . the statements following the reserved word else are executed.enter: Read(Ent ry). Examples: if Interest > 25 tben Usury : = True else TakeLoan : = OK.2 Case Statement The case statement consists of an expression (the selector) and a list of statements. please re. if (Entry < 0) or (Entry> 100) tben begin Write( 'Range is 1 to 100. or. The else clause is an expansion of standard Pascal. It specifies that the one statement be executed whose case label is equal to the current value of the selector. If none of the case labels contain the value of the selector.e.1 If Statement The syntactic ambiguity arising from the construct: if expr1 then if expr2 then stmt1 else stmt2 is resolved by interpreting the construct as follows: ifexpr1 then begin if expr2 then stmtT else stmt2 end I. each preceded by a case label of the same type as the selector.

2.). If the number of repetitions is known beforehand. Otherwise the while or the repeat statement should be used. .2. Writeln('We are at war'). end. "* case Year of Min .Answer Result.Result.Case Statement 7.Answer / Result. all scalar types except real. the for statement is the appropriate construct to express this situation.PostWorldWar2 Wri te In( 'Bui lding a new world.. · .e.Answer + Result.. . . . A subrange is written as two constants separated by the subrange delimiter ' . 1946 .e. = WorldWar2. before the repetitions are started.2 A case label consists of any number of constants or subranges separated by commas followed by a colon.. end. Examples: case Operator '+' : Result .PreWorldWar2... i. . The type of the constants must be the same as the type of the selector. else Time . Writeln('The world at peace . STATEMENTS 59 . Max: begin Time .2. '"*' : of · . Valid selector types are all simple types.Answer . end. '. Result Result . ' ). · . /' : Resul t end. 1939: begin Time . The statement following the case label is executed if the value of the selector equals one of the constants or if it lies within one of the subranges. i.3 Repetitive Statements Repetitive statements specify that certain statements are to be executed repeatedly. · . 7.

Examples: for I . Valid types are all simple types. i. If the repetition is to be terminated before the final value is reached. the component statement is not executed at all.3. the initial value.= 1 to NoOfLines do begin Readln(Line) . . for I .it is better programming practise use a while or a repeat statement instead. all scalar types except real. If the initial value is greater than the final value when using the to clause. and the final value must all be of the same type.A[ I] . the control variable equals the final value. The progression can be ascending: to or descending: downto the final value.e. 60 TURBO Pascal Language Manual .. Upon completion of a for statement.2. a goto statement must be used. unless the loop was not executed at all.7.3. Notice that the component statement of a for statement must not contain assignments to the control variable. The control variable. = 2 to 100 do if A[ I] > Max then Max .1 For Statement The for statement indicates that the component statement is to be repeatedly executed while a progression of values is assigned to a variable which is called the control variable. or if the initial value is less than the final value when using the downto clause. in which case no assignment is made to the control variable. although such constructs are not recommended .ShortLines + 1 else LongLines := LongLines + 1 end.1 For Statement 7. if Length(Line) < Limit then ShortLines .2.

until Up]ase(Answer) in [ 'Y' .3. STATEMENTS 61 .t Wri tee ~M. Read(Answer) . 7.2 7.While statement 7. The statement is repeatedly executed as long as expression is True. The sequence of statements between the reserved words repeat and until is executed repeatedly until the expression becomes true. {process this sample by the Process procedure} end. If its value is false at the beginning. As opposed to the while statement.. the repeat statement is always executed at least once. 'De lete thi s item? (YIN)'). Process. the statement is not executed at all. as evaluation af the condition takes place at the end of the loop.2.2 While statement The expression controlling the repetition must be of type Boolean. 'N']. Examples: while Size> 1 do Size .2. Example: repea. while ThisMonth do begin ThisMonth := CurMonth SampleMonth.3 Repeat Statement The expression controlling the repetition must be of type Boolean.3.3.2.Sqrt(Size).

3.7.3 Repeat Statement Notes: 62 TURBO Pascal Language Manual .2.

SCALAR AND SUBRANGE TYPES 8 8.Multi. Sep. Oct . Scalar types constitute a finite and linear ordered set of values. May. the following is true: Club < Diamond < BBart < Spade SCALAR AND SUBRANGE TYPES 63 . and (= can be applied to all scalar types.Diamond.Wed.e. Heart. 8. Boolean. For the above type card. You are already acquainted with the standard scalar type Boolean which is defined as: type Boolean = (False. Examples: type Operator Day Month Card (Plus. Dec). (Jan. The relational operators =.Sat. >=.Aug. (Club. Jun. Variables of the above type Card can assume one of four values.Fri.Nov.Sun).1 Scalar Type Apart from the standard scalar types (Integer. or Spade. and Byte). (. Feb.BBart. Real. also called declared scalar types. Reals may not always be used in the same context as other scalar types. The values of the new type will be represented by identifiers. The ordering of the scalar type is used as the basis of the comparison. Pascal supports user defined scalar types. i. (>. Therefore. (Mon. SCALAR AND SUBRANGE TYPES The basic data types of Pascal are the scalar types.Divide). Diamond. The definition of a scalar type specifies.Thur.Tues. as long as both operands are of the same type (reals and integers may be mixed). it does not conform to this definition.Apr. the order in which the values are introduced in the type definition. Mar . in order.Spade). Although the standard type Real is included as a scalar type. which will be the constants of the new type.Minus. >. all of its possible values. namely Club. Char.True). Jul .

Sparkling). West). 64 TURBO Pascal Language Manual . 'A' . A subrange of type Real is not allowed. East. Examples: type HemiSphere World Compas sRange Upper Lower Degree Wine (North. The type World is a subrange of the scalar type HemiSphere (called the associated scalar type). (Red. The first constant specifies the lower bound and must not be greater than the second constant. (East.8. Whi te. The associated scalar type of CompasRange is Integer.. Ke Iv). 'Z'. which is defined as: type Byte". being restricted only in its range of values. 0 . 8.1 Scalar Type The following standard functions can be used with arguments of scalar type: Suee(Diamond) The successor of Diamond (Heart). The result type of Ord is Integer. Ord(Diamond) The ordinal value of Diamond (1 [as the ordinal value of the first value of a scalar type is 0]). the upper bound.. A subrange type retains all the properties of its associated scalar type. Such types are called subranges. 360. 255. You already know the standard subrange type Byte.. Pred(Diamond) The predecessor of Diamond (Club). (Ce Ie. 'z'. The definition of a subrange simply specifies the least and the largest value in the subrange. South.2 Subrange Type A type may be defined as a subrange of another already defined scalar type. Rose. 'a' .. and the associated scalar type of Upper and Lower is Char. West) 0 . Fahr. The result type of Succ and Pred is the same as the argument type. Ream.

When an assignment is made to a scalar or a subrange variable while this directive is active ({ $R+}). Furthermore. Standard Pascal does not provide a way to reverse this process. Retyping is achieved by using the type identifier of the desired type as a function designator followed by one parameter enclosed in parentheses. a value of a scalar type may be converted into a value of another scalar type.1 and 8. Assuming the type definitions in sections 8. It is recommended to use this setting as long as a program is not fully debugged. Another advantage of defined types and subrange types is that they often save memory. The parameter may be a value of any scalar type except Real. no checking is performed. TU RBO Pascal allocates only one byte of memory for variables of a defined scalar type or a subrange type with a total number of elements less than 256.2. with the same ordinal value. run time checks are included in the program code (see section 8. by means of the Retype facility. SCALAR AND SUBRANGE TYPES 65 .4) to verify the values assigned to defined scalar variables and subrange variables. integer subrange variables. where lower and upper bounds are both within the range 0 through 255.2 The use of defined scalar types and subrange types is strongly recommended as it greatly improves the readability of programs. Similary.3 Type Conversion The Ord function may be used to convert scalar types into values of type integer. i. In TURBO Pascal.e. i. The default setting is {$R -}. 8. a way of converting an integer into a scalar value.4 Range Checking The generation of code to perform run-time range checks on scalar and subrange variables is controlled with the R compiler directive. then: Integer(Heart) Month(l0) HemiSphere( 2) Upper( 14) Degree( 3) Char( 78) Integer( '7' ) 2 Nov East '0' Kelv 'N' 55 8. assignment values are checked to be within range.Subrange Type 8. occupy only one byte of memory.e.

Dig3: digit.5. {invalid but causes no errod type Digit end. = 0 . 9. {invalid but causes no error} {$R+} Dig3 .8. {invalid and causes a run time errod {$R. 66 TURBO Pascal Language Manual . . Var Dig1. {valid as Dig1 + 3 <= 9} Dig3 · .} Dig3 . begin {valid} Dig1 · .55..Dig1 + 3.47. .4 Range Checking Example: program Rangecheck. Dig2 · .Dig2.167.

STRING TYPE 67 . 9. function designators.e. The plus-sign may be used to concatenate strings. whereas the number of elements in an array is fixed. Sc reenLine = strin. a run-time error occurs. and operators. The definition consists of the reserved word string followed by the maximum length enclosed in square brackets. STRING TYPE TURBO Pascal offers the convenience of string types for processing of character strings. the length must always be specified. one major difference between these: the number of characters in a string (i. the length of the string) may vary dynamically between 0 and a specified upper limit. the maximum length of strings of that type.1 String Type Definition The definition of a string type must specify the maximum number of characters it can contain. 9. String variables occupy the defined maximum length in memory plus one byte which contains the current length of the variable. The Concat function (see section 9. string variables. The length is specified by an integer constant in the range 1 through 255.e. String types are structured types.5) performs the same function.g[ 80] . i.STRING TYPE 9 9. sequences of characters.2 String Expressions Strings are manipulated by the use of string expressions. String expressions consist of string constants. and are in many ways similar to array types (see section 10). The individual characters within a string are indexed from 1 through the length of the string. There is. Example: type Fi leName strin. but the + operator is often more convenient.g[ 14] . If the length of the result is greater than 255. however. Notice that strings do not have a default length. i.e.

'. If the strings are of dif--ferent length. Line := 'Many happy returns on your' + .' + '456' 'A ' + 'B' + ' C ' + 'D = 'TURBO Pascal' = '123.456' ='A BCD' The relational ope--rators =. Example: . E.g.3 String Assignment The assignment operator is used to assign the value of a string expression to a string variable. the variable will only contain the five leftmost characters: 'fifti'. 123' + '. but equal up to and including the last character of the shortest string. If the maximum length of a string variable is exceeded (by assigning too many characters to the variable). the re-suit is a Boolean value ( True or False). if the variable Age above was declared to be of type stringl51. (>. the exceeding characters are truncated. Strings are equal only if their lengths as well as their contents are iden-ti--cal. then the shortest string is considered the smaller.. and (= are lower in precedence than the concatenation operator.9. then after the assignment. When comparing two strings. 68 TURBO Pascal Language Manual . Examples: 'A' < 'B' 'A' > 'b' '2' < '12' 'TURBO' = 'TURBO ' 'TURBO ' = 'TURBO ' 'Pascal Compiler' < 'Pascal compiler' is true is false is false is true is false is true 9.Age + ' birthday.Age := 'fiftieth'. single cha--racters are compared from the left to the right. >=. When applied to string operands. (.2 String Expressions Example: 'TURBO ' + 'Pascal' . >.

If St has the value 'ABCDEFG' then: Insert ( 'XX' . Pos .4 9. If Pos is greater than Length( Target). and Pos is an in-teger ex--pression. St is a string variable and both Pos and Num are integer expres--sions.String Procedures 9. If an attempt is made to delete characters beyond the end of the string (j. 2.4. If Pos is outside the range 1 .4.10) will give St the value 'A'.Num ) Delete removes a sU. Pos + Num exceeds the length of the string). 255.e. 2.. 9.. 3) will give St the value 'ABXXCDEFG' STRING TYPE 69 .2 Insert Syntax: Insert ( Obj.St. If Pos is out--side the range 1. Obj is a string expression. If the result is longer than the maximum length of Target. Pos ) Insert inserts the string Obj into the string Target at the position Pos. 4) will give St the value 'AFG'. then excess characters will be truncated and Target will only contain the left--most characters. Target is a string variable. If Pos is greater than Length ( St ). a run time error occurs. only charac--ters within the string are deleted.1 Delete Syntax: Delete ( St . If St has the value 'ABCDEFG' then: Delete(St. Target. then obj is conca--tenated to Target. a run time error occurs. Delete(St. no charac--ters are removed. 255.4 String Procedures The following standard string procedures are available in TURBO Pascal: 9.bstring con--taining Num characters from St starting at po--sition Pos.

70 TURBO Pascal Language Manual . and X is a Real variable. If no errors are detected. the variable Code is set to O. If I has the value 1234 then: Str(I :5. 8-bit systems only: a function using the Str procedure must never be called by an expression in a Write or Writeln statement. and Str. Neither leading nor trai--ling spaces are allowed.) and stores this value in Var. Otherwise Code is set to the position of the first character in error.Var is a string variable.6.4. Var must be an Integer or a Real variable and Code must be an integer variable.3 Str 9. Value is a write parameter of type integer or of type real.Resul t) gives X the value 2500 and Result the value 0 8-bit systems only: a function using the Var procedure must never be called by an expression in a Write or Writeln statement. then: Val (St.4 Val Syntax: Val ( St . St must be a string expressing a nume--ric value according to the rules applying to numeric constants (see section 4. If X has the value 2. Var . Write parameters are ex--pres-sions with special formatting commands (see sec--tion 14.Resul t) gives I the value 234 and Result the value 0 If St has the value '12x' then: Val (St. and the value of Var is unde--fined.9.5E4 then: Str(X:10:0.St) givesSt the value' 2500' .Resul t) gives I an undefined value and Result the value 3 If St has the value '2.3 ). I . Code) Val converts the string expression St to an integer or a real value (de-pending on the type of the variable Va. 9.5E4'. I . X.St) givesSt the value' 1234'.2).4.3 Str Syntax: Str ( Value. St ) The Str procedure con--verts the numeric value of Value into a string and stores the result in St. If St has the value '234' then: Val (St.4.

As explained in sec--tion 9.1 Copy Syntax: Copy (St .e.' PASCAL'. If the length of the result is greater than 255. Num ) Copy returns a substring con--taining Num characters from St starting at po-sition Pos.10) returns the value 'DEFG' Copy(St. 4.5. sa.5 9.. Pos + Num exceeds the length of the string)' only the charac-ters within the string are returned.St2) returns the value 'TURBO PASCAL is fastest' STRING TYPE 71 . If an attempt is made to get characters beyond the end of the string (i. 3. the + operator can be used to obtain the same result. StN). Concat is in--cluded only to maintain compa-tibility with other Pascal compilers. 4.3. a run-time error occurs. the empty string is returned.5 String Functions The following standard string functions are available in TURBO Pascal: 9. Pos .2 Concat Syntax: Concat (St1 .5.. If Pos is outside the range 1. St is a string expression and both Pos and Num are integer expressions. often more conveniently.String Functions 9. The arguments may be any number of string expressions se--pa--rated by commas ( St2 . St2 { . If St1 has the value' TURBO' and St2 the value 'is fastest' then: Concat(Stl. If St has the value 'ABCDEFG' then: Copy(St. StN } ) The Concat function returns is a string which is the concatenation of its arguments in the order in which they are specified. 2) returns the value 'DE' 9. If Pos exceeds the length of the string. a run time error occurs. 2) returns the value 'CD' Copy(St. 255.

i. Obj and Target are string expressions.5. The result is an integer denoting the position within Target of the first character of the matched pat--tern.e. Pas returns O.5.3 Length Syntax: Length ( St ) Returns the length of the string expression St.St) returns the value 0 72 TURBO Pascal Language Manual .5. If the pattern is not found. The type of the result is integer.St) returns the value 4 pose 'H' .3 Length 9. The position of the first character in a string is 1. If St has the value '123456789' then: Length(St) returns the value 9 9.9. the number of cha--rac-ters in St. and the type of the result is inte--ger. If St has the value 'ABCDEFG' then pose 'DE' . Target) The Pas function scans the string Target to find the first occurrence of Obj within Target.4 Pos Syntax: Pos ( Obj .

STRING TYPE 73 . strings and characters may be mixed in expressions. otherwise a run-time error occurs. When the range check compiler directive R is active ({ $R+}). enclosed in square brackets. and assignments beyond the current length will not affect the actual value of the string variable. a char value may be specified instead and vice versa. however. Examples: Buffer[ 5] Line[Length(Line)-l] Ord(Line[0] ) As the first character of the string (at index 0) contains the length of the string. code is generated which insures that the value of a string index expression does not exceed the maximum length of the string variable. It is. whenever a string value is expected. it is the responsibility of the programmer to check that it is less than the maximum length of the string variable.Strings and Characters 9. to the string variable. When a character is assigned a string value.6 9. This is achieved by appending an index expression of type integer. Furthermore. Length(String) is the same as Ord(String[0]). the length of the string must be exactly one. Thus.6 Strings and Characters String types and the standard scalar type Char are compatible. If assignment is made to the length indicator. The characters of a string variable may be accessed individually through string indexing. The characters thus read are random. still possible to index a string beyond its current dynamic length.

6 Strings and Characters Notes: 74 TURBO Pascal Language Manual .9.

Examples: type Day = (Mon.Straight. 50.Player3.Two. FullHouse.TwoPair. arr~[Players] of LegalBid. ar~[Players] of Hand. followed by the reserved word of.Tue.RSF).Three. Flush. : = Flush. arr~[1 . followed by the component type.Sun) Var WorkHour arr~[1 .ARRAY TYPE 10 10. called the component type or the base type. (One. Bid.. Four.Sat.Thu. ARRAVTYPE An array is a structured type consisting of a fixed number of components which are all of the same type.Wed. and their type is called the index type.200.Pair. Each component can be explicitly accessed by indices into the array. enclosed in square brackets. ARRAY TYPE 75 .Fri. Indices are integer expressions within square brackets suffixed to the array identifier. 100. 7] of Day. 1. Week type Players Hand LegalBid Bid Var Player Pot (Player1. An array component is accessed by suffixing an index enclosed in square brackets to the array variable identifier: Player[Player3] Pot [Player3] := Player[Player4] Pot [Player4] := : = FullHouse.1 Array Definition The definition of an array consists of the the reserved word array followed by the index type. StraightFlush. 10.Player4).Player2. 8] of Integer. ..

Spade. possible to define multidimensional arrays in terms of previously defined array types. The default mode is passive.. and the { $R+} setting causes all index expressions to be checked against the limits of their index type.Five.Clubs. the component type may be another array. A multidimensional array may be defined more conveniently by specifying the multiple indices thus: type AIICards = array[Suit. i..10] is equivalent to Deck[Hearts] [10] It is.Ace).1 Array Definition As assignment is allowed between any two variables of identical type.1 .Diamonds). Such a structure is called a multidimensional array. (Hearts. Suit AIlCards Var Deck: AIlCards.2 Multidimensional Arrays The component type of an array may be any data type. A similar abbreviation may be used when selecting an array component: Deck[Hearts.10. 76 TURBO Pascal Language Manual . i. entire arrays can be copied with a single assignment statement. Ten. Six.King. array[Suit] of array[1 . 13] of Card.Three.Queen. of course.Knight.Nine. {$R-l. Seven. The R compiler directive controls the generation of code which will perform range checks on array index expressions at run-time.e.Four. Example: type Card (Two. 10. 13] of Card. Eight .e.

Multidimensional Arrays 10. arrays may be compared and manipulated in the same way as strings. In TURBO Pascal. and string constants may be assigned to character arrays. NewTownScool: Scool.P.3 Character Arrays Character arrays are arrays with one index and components of the standard scalar type Char. J].4 Predefined Arrays TURBO Pascal offers two predefined arrays of type Byte.. J changed class} C lassA[Vacant] : =ClassB[ p] . NewTownScool[5] [211: '=Peter Brown'. all of the following assignments are legal: ClassA[J] :='Peter'. 30] of Pupils. NewTownScoo I [8.. as long as they are of the same length. String variables and values computed from string expressions cannot be assigned to character arrays. arr~[l . These are discussed in appendices A and B .Vacant ClassA. 10. 100] of Class. character arrays may participate in string expressions. Character arrays may be thought of as strings with a constant length.2 Example: type Pupils Class Scool string[ 10] . called Mem and Port. ARRAY TYPE 77 . J] : =NewTownScoo I [7. Thus. ClassB Class. arr~[l . in which case the array is converted into a string of the length of the array. After these definitions. {pupil no. Var Integer J. {pupil no. which are used to access CPU memory and data ports. P changes Class and numbed 10.

10.4 Predefined Arrays Notes: 78 TURBO Pascal Language Manual .

31.Mar. and Yearare field identifiers. Var Bi rth: Date. As record components may be of any type.. Month. assignment is allowed between entire records of identical types..Month .5] of date. The field list is a sequence of record sections separated by semi-colons. Year: 1900 . Note that. Month: (Jan. WorkDay: array[ 1. . similar to array types. called fields. Example: type Date record Day: 1. each consisting of one or more identifiers separated by commas and terminated by a colon and a type identifier. RECORD TYPE A record is a structure consisting of a fixed number of components. A fieid identifier must be unique only within the record in which it is defined. A field is referenced by the variable identifier and the field identifier separated by a period. end.RECORD TYPE 11 11. Dec). . constructs like the following record of records of records are possible: RECORD TYPE 79 .Year := 1950. Examples: Birth. Oc t . Each record section thus specifies the type and identifier for one or more fields. 11. WorkDay[Current] := workDay[Current-1]. Fields may be of different type and each field is given a name.Apr.1 Record Definition The definition of a record type consists of the reserved word record succeeded by a field list and terminated by the reserved word end.Jun. 1999. July . Sep.Aug. the field identifier. Birth. Day. which is used to select it.Jun.Feb.MaY.Nov.

= Person record ID: Name. Time: Date. end Var Salary. end.Oct. Fee: Wages. Salary. record Day: 1. Year: 1900 .Individual.Overtime .May. Weekend: Integer end.31. Individual.Feb.. Time : = Fee. record NormalRate.Dec). 3] of string[16].Aug.ID.950. the following assignments are legal: Salary : = Fee.11. Month: (Jan. ChristianNames: arr~[1 . Individual. end. end. 1999... JulY. Time. OverI'ime.Mar. NightTime.1 Record Definition type Name Rate Date record Fami lyName: string[ 32].Cost.Jun. Salary. Wages record Individual: Person.Nov. Cost: Rate.Apr.FamilyName := 'Smith' 80 TURBO Pascal Language Manual . Salary. Assuming these definitions. .Sep.

the maximum number of records which may be 'opened' within one block. it would often be easier if we could access individual fields in a record as if they were simple variables. without the record variable identifier: wi th Salary do begin Individual : = NewEmployee. i. depends on your implementation and is discussed in appendices A and B . i. Cost := StandardRates. end This is equivalent to: with Salary do with Individual do with ID do The maximum 'depth' of this nesting of with sentences. i. ChristianNames[l] := 'James'.2 11 . This is the function of the with statement: it 'opens up' a record so that field identifiers may be used as variable identifiers.e. ID do begin Fami lyName : = 'Smi th'.e. end. Within a with statement. records of records may be 'opened' as shown here: with Salary. Individual. A with statement consists of the reserved word with followed by a list of record variables separated by commas followed by the reserved word do and finallya statement.e. a field is designated only by its field identifier.2 With Statement The use of records as describes above does sometimes result in rather lengthy statements.With Statement 11. Records may be nested within with statements. RECORD TYPE 81 .

Bi rtbDate: Date. if Passenger is a variable of type Person. and of the types Name and Date.3 Variant Records 11.3 Variant Records The syntax of a record type also provides for a variant part. statements like the following are perfectly legal: Passenger. the following record allows the field CitizenShip to have different structures depending on whether the value of the field is Citizen or Alien: type Person = record PersonName: Name. 82 TURBO Pascal Language Manual . Assuming the existence of the type: Origin = (Citizen. alternative record structures which allows fields of a record to consist of a different number and different types of components.11. Alien). usually depending on the value of a tag field. case CitizenShip: Origin of Citizen: (BirthPlace: Name). DateOfEntry: Date. followed by labels corresponding to each possible value of the tag field.e. A variant part consists of a tag-field of a previously defined type.CitizenShip := Citizen. Each label heads a field list which defines the type of the variant corresponding to the label. PortOfEntry: Name) end In this variant record definition. Thus. the tag-field is an explicit field which may be selected and updated like any other field. PersonName do if CitizenShip = Alien then writeln(FamiIYName). Al ien: (CountryOfOrigin: Name. Permi ttedUnt i I: Date. i. wlthPassenger. whose values determine the variant.

must always precede the variant part. Actually. the field DateOfEntry can be accessed even if the value of the tag field CitizenShip is not Alien. A record can only have one variant part. Such record variants are known as free unions. Thus. the tag field identifier may be omitted alltogether. i. the fields PersonName and BirthDate are the fixed fields. the part containing the common fields. RECORD TYPE 83 .e. The use of free unions is infrequent and should only be practiced by experienced programmers. The maintenance of tag field values is the responsibility of the programmer and not of TURBO Pascal.Variant Records 11. leaving only the type identifier. I n the above example. even if they will enclose nothing.3 The fixed part of a record. in the Person type above. the parentheses must be present. as opposed to record variants with tag fields which are called discriminated unions. In a variant.

3 Variant Records Notes: 84 TURBO Pascal Language Manual .11.

called the base type.5. There are three operations involving sets. Each object in such a set is called a member or an element of the set. The members of a set must all be of the same type.2.3.3. SETTVPE A set is a collection of related objects which may be thought of as a whole.3.7].3. then the first set is said to be included in the second. In the examples above.4.3.7] and [2. similar to the operations addition.5.7][2.4. 3) is included in 2).3.1] are all equal. i.1 Set Type Definition Although in mathematics there are no restrictions on the objects which may be members of a set. Pascal only offers a restricted form of sets.SET TYPE 12 12.5. RECORD TYPE 85 . Examples of sets could be: 1) All integers between and 100 2) The letters of the alphabet 3) The consonants of the alphabet Two sets are equal if and only if their elements are the same. and the base type must be a simple type.4] is [1.4]. a 12.e. any scalar type except real. Thus. If the members of one set are also members of another set. multiplication and subtraction operations on numbers: The union (or sum) of two sets A and B (written A+B) is the set whose members are members of either A or B. For instance.5. There is no ordering involved. A set type is introduced by the reserved words set of followed by a simple type. The intersection (or product) of two sets A and B (written A*B) is the set whose members are the members of both A and B.7] and [2. For instance.3. the intersection of [1.1] and [3.5. The relative complement of B with respect to A (written A-B) is the set whose members are members of A but not of B.7].5. [5. [1. the union of [1 . so the sets [1.4] is [1.3.51.3.4] is [3.

which. '0'] [X. and enclosed in square brackets. '9' ] [1.Green.12] [] The last example shows the empty set... 10..4. the maximum number of elements in a set is 256.5] [ 'A' .. The set [1 .. and set operators.2 Set Expressions Set values may be computed from other set values through set expressions..1 S~t Constructors A set constructor consists of one or more element specifications.12. 'a' . '0' .Blue).Y) denotes the empty set.. AdditiveColors = set of (Red.Y] [X . An element specification is an expression of the same type as the base type of the set. or a range expressed as two such expressions separated by two consecutive periods (. is compatible with all set types. y] [1. 'Z'.. 'Z' . 86 TURBO Pascal Language Manual . Set expressions consist of set constants.. ).3. In TURBO Pascal.. . 'R'. separated by commas. as it contains no expressions to indicate its base type. Fri. IfX>Y then [X . 12. 'B'. WorkWeek = set of Mon . 'U'. and the ordinal values of the base type must be within the range 0 through 255.3 .2.1 Set Type Definition Examples: type DaysOfMonth = set of 0 . 'z' .. Letter = set of 'A' .5]. 31. Characters = set of Char. 5) is equivalent to the set [1.2. 12. Examples: ['T'. set constructors. set variables.

Set difference. >= True if the second operand is included in the first operand. The second operand is of a set type.2. otherwise it is false.Set Operators 12.2 12. Test on set membership. and the first operand is an expression of the same type as the base type of the set.2. There is no operator for strict unclusion. the test: if (Ch= 'T') or (Cll: 'U') or (Ch= 'R') or (Ch= 'B') or (Ch= '0' ) can be expressed much clearer as: Ch in ['T'. 'U'. Set union.[ '8' . <= IN True if the first operand is included in the second operand. but it may be programmed as A*B=[].. '0'] And the test: i f (Ch >= ' 8') and (Ch < = ' 9') then is better expressed as: i f Ch in. 3) <> Test on inequality. Set expressions are often useful to clarify complicated tests. 'R'.2 Set Operators The rules of composition specify set operator precedences according to the following three classes of operators: 1) 2) * + Set intersection. The result is true if the first operand is a member of the second operand. 'B'. ' 9'] then RECORD TYPE 87 . Test on equality. For instance.

. end. begin AIIChars : = [0 . NoPrint.3 Set Assignments Values resulting from set expressions are assigned to set variables using the assignment operator . 127. 127]. .3 Set Assignments 12. 31.. 88 TURBO Pascal Language Manual .12. NoPrint : = [0 .. Examples: type ABCII Var = set of 0 .AIlChars: ASCII.. Print .127]. Print : = AllChars .NoPrint.

A typed constant may be used exactly like a variable of the same type. TYPED CONSTANTS Typed constants are a TURBO speciality. As a typed constant is actually a variable with a constant value. it cannot be used in the definition of other constants or types. Contrary to untyped constants. In the definition the typed constant identifier is succeeded by a colon and a type identifier. 13.TYPED CONSTANTS 13 13. The use of a typed constant saves code if the constant is used often in a program. of course. Max] of integer TYPED CONSTANTS 89 . because the value of a typed constant is defined. not to assign values to typed constants whose values are actually meant to be constant. Care should be taken. as Min and Max are typed constants.1 Unstructured Typed Constants An unstructured typed constant is a constant defined as one of the scalar types: const NumberOfCars: Integer = 1267.2). Xon: Char = ~Q. whereas the value of a variable is undefined until an assignment is made.67.2. because a typed constant is included in the program code only once. Typed constants are defined like untyped constants (see section 5. except that the definition speficies not only the value of the constant but also the type. the following construct is illegal: const Min: Integer Max: Integer type 0. which is then followed by an equal sign and the actual constant. Thus. 50. Heading: string[7] = 'SECTION'. Range: array[Min . whereas an untyped constant is included every time it is used. Interest: Real = 12.. Typed constants may thus be used as 'initialized variables'. a .typed constan't may be used in place of a variable as a variable parameter to a procedure or a function.

Examples: type Status (Act ive. The example defines the array constants Stat.13. '6'.. Character array constants may be specified both as single characters and as strings. the definition: const Digits: arr~[0 . '2'. may be expressed more conveniently as: const Digits: arr~[0 . They are often used to provide initialized tables and sets for tests. The following sections describe each type in detail.2 Structured Typed Constants Structured constants comprise array constants. '9'). const Stat: StringRep = ('active'. StringRep ar~[Status] of string[7]. Thus. 'waiting'). The components of Stat are: Stat [Act ive] Stat[Passive] Stat [Wai t ing] 'active' 'passive' 'waiting' The component type of an array constant may be any type except File types and Pointer types. Wai t ing).2.1 Array Constants The definition of an array constant consists of the constant identifier succeeded by a colon and the type identifier of a previously defined array type followed by an equal sign and the constant value expressed as a set of constants separated by commas and enclosed in parentheses. '4'. '1'. 90 TURBO Pascal Language Manual . '7'. which may be used to convert values of the scalar type Status into their corresponding string representations. conversions. 13. and set constants. 9] of Char = ('0'. 'paSSive'. '3'.2 Structured Typed Constants 13. Pass i ve.. mapping functions. etc. record constants. '8'. '5'. 9] of Char '0123456789'.

0'). begin Writeln(Maze[0. (CCP.. Example: type Cube = arr~[0 .11. .0].CPM86. as UI (CPM80.MenuMaster).(2. 4] of OS..0.1). .O . 11. Z: end.' 5').Y. 1. Writeln(Maze[l. 7'). integer.Multidimensional Array Constants 13. 11. The innermost constants correspond to the rightmost dimensions. 1. 1.0.0.Unix)..0.2.3 Record Constants The definition of a record constant consists of the constant identifier succeded by a colon and the type identifier of a previously defined record type followed by an equal sign and the constant value expressed as a list of field constants separated by semi-colons and enclosed in parentheses.2 13.O .3». 1. Examples: type Point record X.SomethingElse.0]. 3').5)..2 Multidimensional Array Constants Multidimensional array constants are defined by enclosing the constants of each dimension in separate sets of parentheses. 1] of integer. Writeln(Maze[0. Userlnterface: UI.11. Computer record OperatingSystems: ar~[I . end.((4. TYPED CONSTANTS 91 . .0]. 13. end. Writeln(Maze[0.(6. .' 6'). Writeln(Maze[I. 1.' 4'). Writeln(Maze[ 1. Writeln(Maze[0.2.I. const Maze: Cube = (((O.MSDOS.7)).2.0]. 2'). separated by commas. . 1'). Writeln(Maze[I.

Z:45). 13.. Plane1: arr~[1 . 'Z'].. An element specification must be a constant or a range expression consisting of two constants separated by two consecutive periods (. : . .. ).[. If a record contains fields of file types or pointer types. Z: -7». ' i ' .~". 'Z'. .3 Record Constants canst Origo: Point = (X:0..Y: 10.{. 'z'..2. Vocals Low ['a'. Y:0.Unix).CPM86.. Delimiter: set of Char = [. (X: 10.. Userlnterface: MenuMaster). . 92 TURBO Pascal Language Manual . then constants of that record type cannot be specified. 'e'. then its value must be specified. Low set of 'a' . 'u'.]. Example: type Up set of 'A' .MSDOS. If a record constant contains a variant. . 3] of Point = ((X: 1.Y:4. . Z:5). . / " .?". (X: 100. const UpperCase: Up ['A' . The field constants must be specified in the same order as they appear in the definition of the record type. . '0'. If the variant contains a tag field.13. . and enclosed in square brackets.Y: -78. .4 Set Constants A set constant consists of one or more element specifications separated by commas. 'Y'].2.-... Z:0). SuperComp: Computer = (OperatingSystems: (CPM80. then it is the responsibility of the programmer to specify only the fields of the valid variant.

and each time a component is written to or read from a file. instead the Pascal system keeps track of file accesses through a file pointer. (Le. ProductNames: file of ProductName. FILE TYPES Computer programs frequently produce large amounts of data which is not required until later in the program or even by some other program. data can be written to and read from named units placed on magnetic devices such as diskettes or hard disks. providing random access to any element of the file. The number of components in a file (the size of the file) is not determined by the definition of the file. the file pointer can be moved to any component in the file.1 File Type Definition A file type is defined by the reserved words file of followed by the type of the components of the file. As this data often exceeds the available memory. InStock: Real.. Suppl ier: Integer. FILE TYPES 93 . with reference to the example above. the file pointer of that file is advanced to the next component. Thus. MinStock: Real. except a file type.FILE TYPES 14 14. A file consists of a sequence of components of equal type. and a file identifier is declared by the same words followed by the identifier of a previously defined file type. Product = file of recoDd Name: ProductName. end. The component type of a file may be any type. IterrNumber: Real. These units are called files. Examples: type ProductName = string[80]. Var ProductFile: Product. As all components of a file are of equal length. File variables may appear neither in assignments nor in expressions. file of Product is not allowed). the position of a specific component can be calculated. 14.

i.2 Operations on Files 14. i.3 Reset Syntax: Reset( FiIVar) The disk file of the name assigned to the file variable FilVar is prepared for processing. component no.2. A disk file created by rewrite is initially empty.2 Operations on Files The following sections describe the procedures available for file handling.1 Assign Syntax: Assign( FilVar. Any previously existing file with the same name is erased. 14.14.2.2 Rewrite Syntax: Rewrite( FilVar) A new disk file of the name assigned to the file variable FilVar is created and prepared for processing. and the file pointer is set to the beginning of the file. Assign should never be used on a file which is in use. 14. and the file pointer is set to the beginning of the file. 14. This file name is assigned to the file variable FilVar.2. O. i.e. 94 TURBO Pascal Language Manual . O. Str) Str is a string expression yielding any legal file name. otherwise an I/O error occurs. and all further operation on FiIVar will operate on the disk file Str. The identifier Filvar used throughout denotes a file variable identifier declared as described above.e. it contains no elements. FilVar must name an existing file.e. component no.

Flush should never be used on a closed file. and following each write operation.4 Read Syntax: Read( FilVar.2.2. and thus assures that the sector buffer is written to the disk if any write operations have taken place since the last disk update. the returned number is one greater than the number of the last component). Fi leSize(Fi IVar». 14.6 Seek Syntax: Seek( FilVar. the file pointer is advanced to the next component. Each variable is written to the disk file. and following each read operation. FILE TYPES 95 .Read 14. Var) Var denotes one or more variables of the component type of FilVar. separated by commas. thus places the file pointer at the end of the file ( FileSize returns the number of components in the file. and as the components are numbered from zero. 14. Flush also insures that the next read operation will actually perform a physical read from the disk file.7 Flush Syntax: Flush( FilVar) Flush empties the internal sector buffer of the disk file FiIVar. separated by commas. n) Seek moves the file pointer is moved to the n'th component of the file denoted by FilVar. Each variable is read from the disk file. The position of the first component is O.2. 14. Var) Var denotes one or more variables of the component type of FilVar.4 14.5 Write Syntax: Write( FilVar. the file pointer is advanced to the next component.2.2. Note that in order to expand a file it is possible to seek one component beyond the last component. The statement Seek(Fi IVar. n is an integer expression.

9 Erase Syntax: Erase( FilVar) The disk file associated with FilVar is erased. If the file is open. 96 TURBO Pascal Language Manual .8 Close Syntax: Close( FilVar) The disk file associated with FilVar is closed. otherwise it returns False: function Exist(FileName: Name): boolean. 14. i. {$1 .e. Var Fi 1: file. The following function returns True if the file name passed as a parameter exists. {$1+ } Exist := OOresult 0) end. FileName). it is good programming practice to close the file before erasing it.2. multiple occurrences of the same name may result. and further operations on FilVar will operate on the file with the new name.14. Str) The disk file associated with FilVar is renamed to a new name given by the string expression Str.} Reset(Fil). even if it has only been read from.10 Rename Syntax: Rename( FilVar. Rename should never be used on an open file.2.8 Close 14. The disk directory is updated to show the new name of the file. begin Assign(Fil. 14. if the file has been reset or rewritten but not closed. and the disk directory is updated to reflect the new status of the file. Notice that in multi-user environments it is often necessary to Close a file.2. If it does. Notice that it is the programmer's responsibility to assure that the file named by Str does not already exist.2.

File Standard Functions 14. i. The first component of a file is O. the Assign procedure must be called to assign the file name to a file variable.4 Using Files Before using a file. = FILE TYPES 97 . This call will set the file pointer to point to the first component of the disk file. If not.e.e. 14.3. i.3. 14. After Rewrite. FileSize(FiIVar) is O. the file is empty.3 File Standard Functions The following standard functions are applicable to files: 14.3 14. FilePos(FiIVar) O. Before input and/or output operations are performed. 14. EOF returns False. the file must be opened with a call to Rewrite or Reset.2 RlePos Syntax: FilePos( FilVar) An integer function which returns the current position of the file pointer.1 EOF Syntax: EOF( FilVar) A Boolean function which returns True if the file pointer is positioned at the end of the disk file.3 RleSize Syntax: FileSize( FilVar) An integer function which returns the size of the disk file expressed as the number of components in the file. If FileSize(FiIVar) is zero.3. beyond the last component of the file.

98 TURBO Pascal Language Manual . it should always call the Close procedure. 'PRDIXJCI'.4 Using Files A disk file can be expanded only by adding components to the end of the existing file. begin As s ign(ProductFile. IteIIiNumber: Integer. for I := 1 to MaXNumberOfProducts do begin IteIIiNumber := I.14.DTA. end. InStock: Real. Failure to do so may result in loss of data. Var ProductFile: file of Product. Rewrite(ProductFile). end. FileSize(FilVar». {open the file and delete any data} with ProductRec do begin Name : = " . . 01 ose(ProductFi Ie). end. end. InStock . Supplier: Integer. The program below creates a disk file called PRODUCTS.e. records may be read and written anywhere in the file). The file pointer can be moved to the end of the file by executing the following sentence: Seek(FilVar. Wri te(ProductFi Ie. Product = record Name: ProductName. ProductRec: Product. const MaXNumberOfProducts = 100. When a program has finished its input/output operations on a file. as the disk directory is not properly updated. type ProductName = string[20]. and writes 100 records of the type Product to the file. I: Integer. program Ini tProductFi Ie.0. Supplier : = 0. This initializes the file for subsequent random access (i. ProductRec). UTA' ).

type ProductName = string[20]. Readln(Name) . The program is used to update the Pro duct File created by the program in the previous example. Read(ProductFile.). begin Assign(ProductFile. 'PRODOCT. Suppl ier: Integer. Close(ProductFile). 01 rSc r. ItemNumber: Integer.). Wri te In.. Write('Enter number in stock ('. Write( 'Enter product number (0= stop) . const MaxNumberOfProducts = 100. end.InStock:20:0. MaXNumberOfProducts] do begin Seek(ProductFile. Product = recoDd Name: ProductName.).') . Var ProductFile: file of Product. Readln(Pnr). end. Write( 'Enter supplier number ('. while Pnr in [1 .Pnr-l).4 The following program demonstrates the use of Sseek on random files.ProductRec). InStock: Real.') ').DTA').Using Files 14. Reset(ProductFile). C1 rScr. Seek(ProductFile. Readln(Pnr). Write( 'Enter product number (0= stop) ..). program UpDateProductFi Ie.Name:20. Pnr: Integer. with ProductRec do begin Write( 'Enter name of product ('. end. It emNumber: =Pnr. Write(ProductFile. ReadlnCInStock) .Pnr-l). end. Readln(Suppl ier).ProductRec).Supplier:20. FILE TYPES 99 .') . I. ProductRec: Product.

i. 14. Furthermore. Writes a line marker. and the only operation allowed on the file is sequential reading. skips all characters up to and including the next CR/LF sequence. i. text files are not simply sequences of values of some type. each line being terminated by an end-of-line marker (a CR/LF sequence). 100 TURBO Pascal Language Manual . A Boolean function which returns True if the end of the current line has been reached.5 Text Files Unlike all other file types. Although the basic components of a text file are characters.1 Operations on Text Rles A text file variable is declared by referring to the standard type identifier Text. Lines are processed with the special text file operators Rea dIn . Reset is used to open an existing file for reading. to the textfile. Text files can therefore only be processed sequentially. and the only operation then allowed on the file is the appending of new components to the end of the file. Subsequent file operations must be preceded by a call to Assign and a call to Reset or Rewrite must furthermore precede input or output operations. input and output cannot be performed simultaneously to a text file. Writeln. i. a CR/LF sequence. the position of a given line in a file cannot be calculated. and Eoln : Readln( Filvar) Writeln( Filvar) Eoln( Filvar) Skips to the beginning of the next line.e. As the length of lines may vary. Rewrite is used to create a new text file. if the file pointer is positioned at the CR character of the CR/LF line marker. If EOF( Filvar) is true.5.e. When a new textfile is closed.5 Text Files 14. Character input and output on text files is made with the standard procedures Read and Write. they are structured into lines. The file is further ended by an end-of-file marker (a CtrlZ).14. Eoln( Filvar) is also true. an end-of-file mark is automatically appended to the file.e.

for I := 1 to Length(Line) do begin if Line[ I k>~s then begin Write(Lst.~M).False.5. Write('Enter name of file to list: . Fi leName: begin UnderLine .6 . Read In( F i I eName) . Reset(Fi IVar). while not Eof(FiIVar) do begin Readln(Fi IVar. .Operations on Text Files 14. Line). ExtraLine := " . ExtraLine: Integer.). I := 1. Further extensions of the procedures Read and Write.ExtraLine). the EOF function returns the value True if the file pointer is positioned at the end-of-file mark (the CTRl/Z character ending the file). FILE TYPES 101 . The following sample program reads a text file from disk and prints it on the pre-defined device Lst which is the printer.1 When applied to a text file. Var Text. string[ 14] . Fi IVar: Line. . if UnderLine then Ext raLine . end. which facilitate convenient handling of formatted input and output. are described in section 14. Ass ign(Fi IVar. end. string[ 255] .Line[I]).Ext raLine+~' else ExtraLine := ExtraLine+' '. Fi leName). end else UnderLine : = not UnderLine. The Seek and Flush procedures and the FilePos and FileSize functions are not applicable to text files. {while not Eof} end. I: UnderLine: Boolean. Words surrounded by Ctrl-S in the file are printed underlined: program TextFi leDemo. Writeln(Lst. Write(Lst.

13 and B. and input is obtained from the console input device. The user device. please refer to sections A. Output is sent to the operating system's punch device. TRM: KBD: L5T: AUX: U5R: These logical devices may be accessed through the pre-assigned files discussed in section 14.1 .5. The keyboard device (input only). Input characters are echoed. and input is obtained from the operating system's reader device. The only control character echoed is a carriage return (CR). external devices such as terminals. usually the CRT. the punch and reader devices refer to a modem. and an attempt to Erase such a file will cause an I/O error. Output is sent to the operating system's console output device. this means that each Read or Readln from a textfile assigned to the CON: device will input an entire line into a line buffer. please refer to sections 14. The following logical devices are available: CON: The console device. In short. printers. and input is obtained from the user input routine.3 or they may be assigned to file variables.3 and 14. typically the line priner. The terminal device. usually the keyboard. exactly like a disk file.5. For further details on user input and output. There is no difference between Rewrite and Reset on a file assigned to a logical device. Close performs no function. Output is sent to the user output routine.2 Logical Devices In TURBO Pascal.3. 102 TURBO Pascal Language Manual . The list device (output only). which is echoed as CR/LF. usually the keyboard. the CON: device provides buffered input. Input is not echoed.5. usually the keyboard.2 Logical Devices 14. Output is sent to the operating system's console output device.14. Output is sent to the operating system's list device. Contrary to the TRM: device (see below). Usually.3 . and that the operator is provided with a set of editing facilities during line input. For more details on console input. and modems are regarded as logical devices which are treated like text files. usually the CRT. and input is obtained from the console input device. unless they are control characters. The auxiliary device. Input is obtained from the operating system's console input device.5.6.

the programmer is saved the reset/rewrite and close processes. The following table provides an overview of the operation of Eoln and Eof: On Fi les Eoln is true if next character On Logical Devices if current character is CR or Ctrl-Z is CR or Ctrl-Z or if EDF is true Eof is true if next character character is Ctrl-Z or if phys ical EDF is met if current character is Ctrl-Z I Table 14-1: Operation of EOLN and Eof Similarly. whereas on a logical device it only reads up to and including the first CR.3 Standard Rles As an alternative to assigning text files to logical devices as described above. which means that the system has no way of knowing what character will follow the CR.2 The standard functions Eof and Eoln operate differently on logical devices than on disk files.5. On a disk file. or when physical EOF is encountered. and Eoln returns True when the next character is a CR or a Ctrl-Z. In effect. As you cannot look ahead on a logical device. TURBO Pascal offers a number of pre-declared text files which have already been assigned to specific logical devices and prepared for processing. Thus. the Readln procedure works differently on logical devices than on disk files. Eoln and Eof operate on the last character read instead of on the next character. and the use of these standard files further saves code: FILE TYPES 103 .5. Readln reads all characters up to and including the CR/LF sequence. Eof returns True when the last character read was a Ctrl-Z. The reason for this is again the inability to 'look ahead' on logical devices. Thus.Logical Devices 14. and Eoln returns True when the last character read was a CR or a Ctrl-Z. On a disk file. 14. Eof returns True when the next character in the file is a Ctrl-Z. Eof and Eoln are in fact "Iook ahead" routines.

This file is assigned to either the CON: device or to the TRM: device (see below for further details)' Assigned to the console device (CON :). Readln(Varl). Var2).5. Readln(Con. The default value {$B+} causes the console device (CON:) to be used. Pascal. The primary output file. Notice that the B compiler directive must be placed at the start of the program block. Example: {$B. input should be made from the standard file Kbd: Read(Kbd. If some input/output operations are to use the CON: device. and others the TRM: device. Reset. Rewrite. I n the {$B -} mode. Assigned to the list device (LST:). Assigned to the terminal device (TRM :).1 ). Assigned to the auxiliary device (AU X :). The logical device referred to by the standard files Input and Output is determined by the B compiler directive. output). Notice that the use of Assign. but entries may follow the formats defined by Standard.14. then set the B directive for the most frequently used device and specify the other device explicitly in the remaining calls to i/o procedures. and Close on these files is not only unnecessary. and is thus a global directive which cannot be changed throughout the program text.6. but it does not conform to the standard in all aspects. which provides buffered input with editing facilities (see section 14. Assigned to the keyboard device (KBD:). input and output will instead refer to the terminal device (TRM:) which offers no editing facilities during input.3 Standard Files Input Output Can Trm Kbd Lst Aux Usr The primary input file. Reads from the TRM: device Reads from the CON: device In situations where input is not to be automatically echoed to the screen. This file is assigned to either the CON: device or to the TRM: device (see below for further details).} program ReadAndWri tee input. No differences exist between the console device and the terminal device on output operations. Assigned to the user device (USR:). Var) 104 TURBO Pascal Language Manual . but also illegal.

Suppl ier: Integer. Ch) Read(!nput. Reset(ProductFi Ie). begin Ass ign(ProductFi Ie. type ProductName = string[20]. 'Item: '. Now in stock: '. Close(ProductFile). for I := 1 to MaXNumberOfProducts do begin Read(ProductFile.r ProductFile: file of Product. end.InStock:0:0). ProductRec: Product.ProductRec). Va. Product = record Name: ProductName.3 As the standard files Input and Output are used very frequently. lJi th Produc tRec do begin i f Name< >" then Writeln(Lst. I: Integer. end. FILE TYPES '05 .' " Name:20. they are chosen by default when no file identifier is explicitly stated. 'ffiOIXJCT. .5. From: " Supplier:5. UI'A' ). end. InStock: Real.IterrNumber:5. IterrNumber: Integer. const MaXNumberOfProducts = 100. The following list shows the abbreviated text file operations and their equivalents: Write (Ch) Read(Ch) Writeln Rea dIn Eat Eo In Write (Output. end.Standard Files 14.Ch) Writeln(Output) Rea dIn (Input) Eot(!nput) Eoln(!nput) The following program shows the use of the standard file Lst to list the file ProductFile (see the example on page 99 ) on the printer: program ListProductFile.

In the second case. Var1. VarN) where Var1. then I/O will act on that file. If not. and Writeln which use a special syntax for their parameter lists to facilitate maximum flexibility of input and output.e.14. and Eof is true if the next character is a CtrlZ. The syntax of the Read statement is: Read(Var1. . Write. In particular.6. the variables are input from the text file which is previously assigned to FilVar and prepared for reading. and numeric data.. strings. See section 14. usually the keyboard. Rea din. If the first parameter of an I/O procedure is a variable identifier representing a text file.. Var2. Var2. Eoln is true if the character read was a CR or if Eof is True.3 for more details.. Eoln is true if the next character is a CR or a Ctrl-Z. If the file is a disk file. . 14. . and Eof is true if the character read was a Ctrl-Z. If the file is a logical device (including the standard files Input and Output). Integer or Real. Var2. Read reads one character from the file and assigns that character to the variable.. the variables are input from the the standard file Input. In the first case. VarN) or Read(FiIVar. Input and output on text files is done with the standard procedures Read.. i. A text file may be assigned to any device.5. String.1 Read Procedure The Read procedure provides input of characters. . 106 TURBO Pascal Language Manual .6 Text File Input and Output 14.6 Text File Input and Output Input and output of data in readable form is done through text files as described in section 14. a disk file or one of the standard I/O devices. or physical end-of-file is met. With a variable of type Char. in which case the I/O procedures provide automatic data conversion to and from the basic Char type of text files. parameters may be of different types.5. I/O will act on the standard files Input and Output.... VarN are variables of type Char.

a CR. The following editing facilities are available: . a line is input from the console and stored into a buffer. This allows for editing during entry. special rules apply to the reading of variables. BACKSPACE is usually generated by pressing the key marked BS or BACKSPACE or by pressing Ctrl-H.1 With a variable of type string. TABs. If the input file is assigned to the console device (CON:)' or if the standard file Input is used in the {$B+} mode (default). the next Read or Readln will start with the character immediately following that blank orTAB. The string must be no longer than 30 characters. or LFs preceding the string are skipped.6. Otherwise the numeric string is converted to a value of the appropriate type and assigned to the variable. and the reading of variables then uses this buffer as the input source. If the string does not conform to the expected format. if input from the keyboard is only a CR). or in some cases RUB or RUBOUT. Read reads as many characters as allowed by the defined maximum length of the string. a TAB. Any blanks.2. In that case no new value is assigned to the variable. and the input string is ended with a blank or a TAB. With a numeric variable (Integer or Rea!). When reading from a disk file. On a call to Read or Readln. CRs. The RETURN key is used to terminate the input line. and Eat is true if the string was ended with a Ctrl-Z. Backspaces one character position and deletes the character there. BACKSPACE and DEL.g. Eoln is true if the string was ended with a CR or a Ctrl-Z. and it must be followed by a blank. unless Eoln or Eat is reached first. For both disk files and logical devices. or a Ctrl-Z. This terminating CR is not echoed to the screen. This key may be marked ENTER on some keyboards. A special case of numeric input is when Eoln or Eat is true at the beginning of the Read (e. Ctrl-X Backspaces to the beginning of the line and erases all characters input.Read Procedure 14. DEL is usually generated by the key thus marked. an I/O error occurs. Read expects a string of characters which complies with the format of a numeric constant of the relevant type as defined in section 4. Eoln is true if the character read was a CR or if Eat is True. and Eat is true if the last character read is a Ctrl-Z. or physical end-of-file is met. FILE TYPES 107 . and the variable retains its former value.

Strings will be empty. I.. 108 TURBO Pascal Language Manual . you may lower this limit by assigning an integer in the range 0 through 127 to the predefined variable BufLen. = 14. as opposed to Read. Var1. Var2 •.2 Readln Procedure The Readln procedure is identical to the Read procedure.).. When Readln is reading from the console (standard file Input or a file assigned to CON:). However.14. BufLen is restored to 127.6. 14 chars): . and numeric variables will remain unchanged. the input line is stored with a Ctrl-Z appended to the end of it.6. if fewer values are specified on the input line than the number of variables in Reads parameter list.1 Read Procedure Internally. The syntax of the procedure statement is: Re a dIn (Var1. Readln may also be called without parameters: Readln or Readln(FiIVar) in which case the remaining of the line is skipped. except that after the last variable has been read.. The maximum number of characters that can be entered on an input line from the console is 127 by default. any Char variables in excess will be set to Ctrl-Z.• VarN) or Re a dIn (Fil Var. Thus.e.• VarN) After a Rea dIn • the following Read or Readln will read from the beginning of the next line. After that. 14. the terminating CR is echoed to the screen as a CR/LF sequence. Var2 •.. all characters up to and including the next CR/LF sequence (or the next CR on a logical device) are skipped.. BufLen. Example: Wri tee 'Fi Ie name (max. the remainder of the line is skipped. Notice that assignments to BufLen affect only the immediately following Read. Read(Fi leName).

The character Ch is output.e.6. strings. Var2. In the first case. i. The string S is output right-adjusted in a field which is n characters wide. Arrays of characters may also be output. Depending on the value of B. n denote expressions of type Integer. R Ch S B Ch Ch:n S S:n B B:n I:n FILE TYPES 109 . Var1. the variables are output to the text file which is previously assigned to FilVar. either the word TRUE or the word FALSE is output right-adjusted in a field which is n characters wide. optionally followed by a colon and an integer expression defining the width of the output field. either the word TRUE or the word FALSE is output. denotes an expression of type String. Var2.3 14. VarN (the write parameters) are variables of type Char. The format of a write parameter depends on the type of the variable. m. usually the screen. The character Ch is output right-adjusted in a field which is n characters wide. and numeric values. denotes an expression of type Real.e. the variables are output to the the standard file Output. .. denotes an expression of type Char. Var2.. The decimal representation of the value of I is output. VarN) where Var1. boolean values. i.Write Procedure 14. VarN) or Write(FilVar.3 Write Procedure The Write procedure provides output of characters. Ch is preceded by n -1 blanks... Depending on the value of B. String.6. . Integer or Real. In the following descriptions of the different formats and their effects. the symbols: I. . as they are compatible with strings. The decimal representation of the value of I is output right-adjusted in a field which is n characters wide. The syntax of a Write statement is: Write(Var1. S is preceded by n -length(S) blanks.. and denotes an expression of type Boolean.. . . In the second case. The string S is output. . Boolean.

0). When n is greater than 16 (17 for R < 0. right adjusted in a field n characters wide.digitsEtdd R < 0. and no decimal point.ddddddddd~dd R:n where ~ represents a blank.0: blanks-d. otherwise floating point format is used. d represents a digit. R:n:m The decimal representation of the value of R is output. No decimal part.us or minus.0: ~.ddddddddd~dd _-d.6. and t represents either'+' or'-'. and t represents either p. the field width is minimum 7 characters (8 for R <0. = = 110 TURBO Pascal Language Manual . m must be in the range 0 < m < 24. right adjusted in a field 18 characters wide. using fixed point format with m digits after the decimal point. the number is preceded by n -16 blanks (n -17 for R< 0.14.0). right adjusted in a field n characters wide.0: R < 0. The number is preceded by an appropriate number of blanks to make the field width n. d represents a digit. is output if m is O.0: blanksd.3 Write Procedure R The decimal representation of the value of R is output. using floating point format: R >= 0. digits represents from one to ten digits. The decimal representation of the value of R is output. As at least one digit is output after the decimal point. using floating point format: R >= 0.digitsEtdd where blanks represents zero or more blanks.0).

WPn) A Writeln with no write parameters outputs an empty line consisting of a CR/LF sequence: Writeln or Writeln{File) FILE TYPES 111 . WP2. except that a CR/LF sequence is output after the last value. .Writeln Procedure 14. WPn) or Writeln{FiIVar...4 Writeln Procedure The Writeln procedure is identical to the Write procedure. The syntax of the Writeln statement is: Writeln{Var1. WP2.. . .6. WP1...6.4 14.

An untyped file is declared with the reserved word file: Var DataFi Ie: fi Ie. The transfer starts at the first byte occupied by the variable Var.7 Untyped Files Untyped files are low-level I/O channels primarily used for direct access to any disk file using a record size of 128 bytes. the use of an untyped file is therefore to be preferred if a file variable is required only for Erase. Close should be used to insure proper termination.14. and Flush are allowed on untyped files. After processing. Rename or other non-input/output operations. Var.7. data is transferred directly between the disk file and the variable. Var is any variable. and Reset opens an existing file. The syntax of a call to these procedures is: BlockRead( FilVar. 14. Rewrite creates and opens a new file. An untyped file variable therefore occupies less memory than other file variables. The programmer must insure the programmer to insure that the variable Var occupies enough space to accomodate the entire data transfer. thus saving the space required by the sector buffer required by typed files. As an untyped file is furthermore compatible with any file.1 BlockRead / BlockWrite All standard file handling procedures and functions except Read. A call to BloekRead or BloekWrite also advances the file pointer rees records. In input and output operations to untyped files. Var. Write. A file to be operated on by BloekRead or Block Write must first be prepared by Assign and Rewrite or Reset. rees) where FilVar variable identifier of an untyped file.7 Untyped Files 14. 712 TURBO Pascal Language Manual . rees) BlockWrite( FilVar. Read and Write are replaced by two special high-speed transfer procedures: BloekRead and BloekWrite. and rees is an integer expression defining the number of 128-byte records to be transferred between the disk file and the variable.

DestinationName: Buffer: NoOfRecsToRead. Remaining := FileSize(Source). Close(Dest inat ion). B lockRead( Source.). whi Ie Remaining > 0 do begin if BufSize <= Remaining then NoOfRecsTaRead: =BufSize else NoOfRecsToRead: =Remaining. BufByteSize] of Byte. Rewri te(Dest inat ion). arr~[1 .. SourceName). DestinationName).1 The standard function EOF works as with typed files.7. using a component size of 128 bytes (the record size used by BlockRead and BlockWrite).NoOfRecsToRead). var Source. Write( 'Enter destination file name: .. Buffer . Reset (Source).Buffer. FILE TYPES 113 . Readln(DestinationName). Remaining: Fi Ie. So do standard functions FilePos and FileSize and standard procedure Seek. NoOfRecsToRead) . Remaining : = Remaining-NoOfRecsToRead. The following program shows the use of an untyped file. begin Wri tee 'Enter source file name: ' ). BlockWrite(Destination. Destination: SourceName. end. const BufSize BufByteSize 200. Assign(Dest inat ion. Ass ign(Source. Integer. 15600.BlockRead / Block Write 14. Readln( SourceName). It reads any disk file and copies its contents to any other disk file: program Fi leCopy. string[14]. end.

When the I directive is passive ({ $I-}). the following standard procedures should be followed by a check of 10resuit to insure proper error handling: Assign BlockRead BlockWri te Chain Close E:<>ase Execute Flush Read Readln Rename Reset Rewri te Seek Write Wri teln 114 TURBO Pascal Language Manual . and an error message indicating the type of error is displayed.14. {$I+} which causes calls to an I/O check routine after each I/O operation. When this is done. like in the following example which continues to ask for a file name until the attempt to reset the file is succesful (Le. Readln( InFi leName). begin repeat Write('Enter name of input file . {$I-} ResetCInFile) {$I+} .InFileName). the error condition is reset and I/O may be performed again. subsequent calls to 10resuit will return zero until the next I/O error occurs. no run time checks are performed.).8 I/O checking 14. if not OK then Writeln('Cannot find file '. An I/O error thus does not cause the program to stop. but suspends any further I/O until the standard function 10resuit is called. Notice that as the error condition is reset when 10resuit is called. until OK. It is now the programmer's responsibility to take proper action according to the type of I/O error. I/O errors then cause the program to terminate. {$I-}. anything else means that an error occurred during the last I/O operation.8 I/O checking The I compiler directive is used to control generation of runtime I/O error checking code. If I/O checking is passive. OK : = CIOresul t = 0). InFi leName). Le. The default state is active. until an existing file name is entered): procedure OpenInFi Ie. AssignCInFile. A zero returned by 10resuit indicates a successful operation. The 10result function is very convenient in situations where a program halt is an unacceptaple result of an I/O error. end. Le. Appendix I lists all error messages and their Numbers.

Var FirstPerson. Dynamic variables serve this purpose as they are generated as the need arises and may be discarded after use. their form and size is predetermined. LastPerson. reco~ Name: string[ 50]. 15. The type Person Pointer is is declared as a pointer to variables of type PersonRecord: type PersonPointer = PersotiRecord = ~PersotiRecord. Next: PersonPointer. Such dynamic variables are not declared in an explicit variable declaration like static variables. i. NewPerson: PersonPointer. and they cannot be referenced directly by identifiers. frequently need the use of a data structure which varies in form and size during execution. This special variable is called a pointer variable. end. a special variable containing the memory address of the variable is used to point to the variable. and they exist throughout the entire execution of the block in which they are declared.1 Defining a Pointer Variable A pointer type is defined by the pointer symbol ~ succeeded by the type identifier of the dynamic variables which may be referenced by pointer variables of this type. however. Instead. Job: string[50]. IPODNTIEIR TYlPlES Variables discussed up to now have been static. POINTER TYPES 115 . The variables NextPerson. Programs.e. The following shows how to declare a record with associated pointers.POINTER TYPES 15 15. LastPerson and NewPerson are thus pointer variables which can point at records of type Person Record.

signed to pointer variables to indicate the absence of a usable pointer. The procedure has one parameter which must be a pointer to variables of the type we want to create.15. A new variable of type PersonRecord can thus be created by the statement: New(Fi rstPerson). nil may also be used in comparisons. 15. The syntax of a call to Mark is: Mark(Var). New variables of any type are allocated with the standard procedure New.3 Mark and Release When a dynamic variable is no longer required by the program. 15. 116 TURBO Pascal Language Manual . Pointers of identical type may also be compared using the relational operators and <>. the heap pointer is moved towards the top of free memory the number of bytes corresponding to the size of the new dynamic variable. returning a Boolean result (True or False). and may be aS. The TURBO Pascal system controls the heap by maintaining a heap pointer which at the beginning of a program is initialized to the address of the first free byte in memory. of course. nil points to no dynamic variable. Variables created by the standard procedure New are stored in a stack-like structure called the heap. have some variables to point at.2 Allocating Variables (New) Before it makes any sense to use any of these pointer variables we must. = The pointer value nil is compatible with all pointer types.1 Defining a Pointer Variable As shown above. The Mark procedure assigns the value of the heap pointer to a variable. the standard procedures Mark and Release is used to reclaim the memory allocated to these variables. the type identifier in a pointer type definition may refer to an identifier which is not yet defined. which has the effect c'f having FirstPerson point at a dynamically allocated record of type Person Record. Assignments between pointer variables can be made as long as both pointers are of identical type. On each call to New.

Name.Next. Release thus discards all dynamic variables above this address.. then the following statements will go through the list and write the contents of each record (FirstPerson points to the first person in the list): _hi Ie FirstPerson <> nil do with FirstPerson~ do begin Writeln(Name.3 where Var is a pointer variable. where Var is a pointer variable. FirstPersonA. Further discussion is deferred to appendices A and B. The pointer variable Heap Top is used only for the purpose of recording and storing the initial value of the heap pointer. It is not possible to release the space used by variables in the middle of the heap. i. Finally. the field Name in the record pointed to by FirstPerson.Job). The following demonstrates the use of pointers to maintain a list of names and related job desires. Its definition as a ~ Integer (pointer to integer) is thus totally arbitrary.e. Then the entire list is printed. 15.' is a '. The syntax is: Re 1ease(Var). end.Mark and Release 15.Name may be read as FirstPerson's. FirstPerson . POINTER TYPES 117 . The Release procedure sets the heap pointer to the address contained in its argument. previously set by Mark. the memory used by the list is released for other use. The standard function MemAvail is available to determine the available space on the heap at any given time.4 Using Pointers Supposing we have used the New procedure to create a series of records of type Person Record (as in the example on the following page) and that the field Next in each record points at the next Person Record created. Names and job desires will be read in until a blank name is entered.

Next : = ni 1. Write( 'Enter profession: . repeat Wri tee 'Enter name: ' ). Name . Next : = NewPerson. 118 TURBO Pascal Language Manual .g[50]. ' FirstPerson := end.g[50] j begin Fi rstPerson : = ni 1. if Name <> " then begfn New(NewPerson) . .4 Using Pointers procedure Jobsj type PersonPointer = ~PersonRecordj PersonRecord = record Name: strin. NewPerson: PersonPointerj Name: strin. <> nil do do is a '. Next. LastPerson : = NewPerson. '.g[ 50]. Wri telnj while FirstPerson with FirstPerson~ begin Write In(Name . end. LastPerson~ . Mark(HeapTop) .Job)j Wri teln.15. until Name = . NewPerson~ .Name. Readln(NewPerson~.).Job). Next: PersonPointerj endj Var HeapTop: ~ Integerj FirstPerson. if FirstPerson = nil then Fi rstPerson : = NewPerson else LastPerson~ . Re lease(HeapTop) j end. LastPerson. Job: strin. Readln(Name).

5 15. and I is an integer expression giving the number of bytes to be allocated. GetMem allows the programmer to control the amount of space allocated. GetMem is called with two parameters: GetMem(PVar. POINTER TYPES 119 . Unlike New. 1) where PVar is any pointer variable. which allocates as much space as required by the type pointed to by its argument.Space Allocation 15.5 Space Allocation The standard procedure GetMem is used to allocate space on the heap.

15.5 Space Allocation Notes: 120 TURBO Pascal Language Manual .

Integer and string[255]). Such parameters are called a value parameter and are declared in the subprogram heading as in the following example. (This and the following examples show procedure headings. A function is rather similar. and Str2 are the formal parameters to which the value of the actual parameters are passed. or designator. The procedure statement or function designator which invokes the subprogram may contain a list of parameters.1 . and changes of the formal parameters have no effect on the actual parameter.Num2: Number. Parameters provide a substitution mechanism which allows the logic of the subprogram to be used with different initial values. The order of parameter passing is the order of appearance in the parameter lists.2). The actual parameter may be any expression. and it is activated from elsewhere in the program by a procedure statement (see section 7. PROCEDURES AND FUNCTIONS A Pascal program consists of one or more blocks. etc. called the actual parameters. Num2. the formal parameter represents a local variable in the subprogram. When parameters are passed by value.PROCEDURES AND FUNCTIONS 16 16. and Num1.) procedure ExampleCNuml. thus producing different results.3. including a variable. Str1. Strl. another is a function (in common called subprograms). Pascal supports two different methods of parameter passing: by value and by reference. The types of the formal and the actual parameters must correspond.2).1 Parameters Values may be passed to procedures and functions through parameters. a procedure is a separate part of a program. These are passed to the formal parameters specified in the subprogram heading. PROCEDURES AND FUNCTIONS 121 . One such block is a procedure.1. Number and Txt are previously defined types (e. is encountered during execution (see section 6. Thus. with the same type as the corresponding formal parameter. each of which may again consist of blocks. which determines the effect that changes of the formal parameters have on the actual parameters. but it computes and returns a value when its identifier.g.Str2: Txt). function headings are slightly different as described i section 1 6. 16.

and are declared as follows: procedure Example(Var Numl .1 Parameters Notice that the type of the parameters in the parameter part must be specified as a previously defined type identifier. Any changes made to the formal parameter is thus made to the actual parameter.. such as an array. When a parameter is passed by reference. Str1.Str2: Txt). the formal parameter in fact represents the actual parameter throughout the execution of the subprogram.16. 500] of Integer. the construct: procedure Select(Model: arr~[1 . A value parameter would require storage for an extra copy of the entire data structure. Thus. the desired type should be defined in the type definition of the block. Thus. its index expression(s) are evaluated when the subprogram is called.Num2 : Number) Value parameters and variable parameters may be mixed in the same procedure as in the following example: procedure Example(Var Num1. Notice that file parameters must always be declared as variable parameters. procedure Select(Model: Range). and the type identifier should then be used in the parameter declaration: type Range arr~[ 1 . Parameters passed by reference are called a variable parameters. All address calculations are done at the time of the procedure call. 500] of Integer). the use of a variable parameter will save both time and storage space. as the only information then passed on to the subprogram is the address of the actual parameter. is to be passed to a subprogram as a parameter. in which Num1 and Num2 are variable parameters and Stf1 and Str2 are value parameters.. When a large data structure. 122 TURBO Pascal Language Manual .Num2: NUmber. if a variable is a component of an array. which must therefore be a variable. and the time involved in copying it. Instead. is not allowed.

directive} {$V. The default active state {$V+} indicates strict type checking.1. Thus. when using variable parameters. Encode(Line1) ..Relaxations on Parameter Type Checking 16.1 16. begin Line1 .2· Untyped Variable Parameters If the type of a formal parameter is not defined. Line2: string[ 100] . Line2 := 'Here is another (longer) secret message'. procedure Encode(Var LineToEncode: WorkString). end.e. the corresponding actual parameter may be any type. irrespective of the length of the formal parameters.1. whereas the passive state { $V -} relaxes the type checking and allows actual parameters of any string length to be passed.} type WorkString = string[255]. Example: program NSA. Enc ode (L ine2). the formal and the actual parameters must match exactly. This means that subprograms employing variable parameters of type String will accept only strings of the exact length defined in the subprogram. i. {this program must be compiled with the $V.1 Relaxations on Parameter Type Checking Normally.1. then that parameter is said to be untyped. the type definition is omitted from the parameter section of the subprogram heading. This restriction may be overridden by the V compiler directive. Var I: Integer.'This is a secret message'. Var Line1: string[80]. begin for I := 1 to Length(LineToEncode) do LinetoEncode[I] := Chr(Ord(LineToEncode[I])-30). end. 16. PROCEDURES AND FUNCTIONS 123 .

. as a parameter to Addr.BestMatrix: Matrix.16. Assuming the declarations: type Matrix = arrayL1. . 50. The Switch Var procedure in the following example demonstrates the use of untyped parameters.AJ!. Size: Integer). Var TestMatrix.1.1. AI[ Count] . Count: Integer. or Move. Var Al: A absolute Alp. end. e. end. It moves the contents of the variable A1 to A2 and the contents of A2 to A 1 . procedure Swi tchVar(Var Alp. ..: A absolute A2p.g. and it may therefore be used only in contexts where the data type is of no significance. type A = array[ 1. Tmp: Byte.BestMatrix. A2[ Count] : = Tmp.25] of Real. SizeOf(Matrix)).A2p. BlockRead/Write. then Switch Var may be used to switch values between the two matrices: SwitchVar(TestMatrix.A2[ Count] .2 Untyped Variable Parameters The untyped formal parameter itself is incompatible with all types. 124 TURBO Pascal Language Manual . or as the address specification of absolute variables. begin for Count := 1 to Size do begin Tmp : = Al[ Count]. Fil/Char. MaxInt] of Byte. .

procedure Compute(Var Data: Matrix. The procedure heading consists of the reserved word procedure followed by an identifier which becomes the name of the procedure. but that standard procedure then becomes inaccessible within the scope of the user declared procedure.1).1 Procedure Declaration A procedure declaration consists of a procedure heading followed by a block which consists of a declaration part and a statement part.2 16. type. The declaration part of a procedure has the same form as that of a program.) The next example shows a program which uses a procedure and passes a parameter to this procedure. (CP/M -80 only: Notice that the A compiler directive must be passive { $A-} when recursion is used. outside which they are not known. optionailly followed by a formal parameter list as described in section 16. A procedure may reference any constant. 16. the formal parameter must be a value parameter. and it takes the form of a compound statement (see section 7. As the actual parameter passed to the procedure is in some instances a constant (a simple expression). declared by the programmer.2. and to any procedures within it.1 . Scale: Real).Y: Integer). Examples: procedure Logon.Procedures 16. the procedure will ex'ecute recursively. If the procedure identifier is used within the statement part of the procedure itself. i. All identifiers declared in the formal parameter list and the declaration part are local to that procedure. variable. Pre-declared procedures are parts of the TURBO Pascal system and may be called with no further declaration. PROCEDURES AND FUNCTIONS 125 .e. The statement part specifies the action to be executed when the the procedure is invoked. This is called the scope of an identifier. procedure Position(X. procedure.2. A userdeclared procedure may be given the name of a standard procedure. see appendix E . or function defined in an outer block.2 Procedures A procedure may be either pre-declared (or 'standard') or user-declared.

J). begin GotoXY(Xl . end. Var I: Integer. would not 126 TURBO Pascal Language Manual .10*I. end. .1 Procedure Declaration program Box. i.16. { of procedure DrawBox } begin C lrScr. . the values of I and J will be switched. In such cases variable parameters are used. end. as in the following example: procedure Switch(Var A.Tmp. GotoXY(X2.Yl. When this procedure is called by the statement: Switch(I.-. GotoXY(Xl .I*2. GotoXY(Xl . Var Tmp: Integer. B . A : = B.4*I). then the statement Swi tch( I. procedure DrawBox(Xl . If the procedure heading in Switch was declared as: procedure SWitch(A.1).Yl). Write('!'). J) change I and J.80. DrawBox(1. Often the changes made to the formal parameters in the procedure should also affect the actual parameters.Y2).B: Integer).Yl+l).). begin Tmp . for I := 1 to 5 do DrawBox(I*4. X2. Y2: Integer). for I := Xl to X2 do Write( .23).e.2.A. for I := Xl to X2 do write('-'). f or I : = Yl + 1 to Y2 do begin GotoXY(Xl. with a value parameter.B: Integer).1. end. Write('!').1). Var I: Integer.

In addition to these.2 16.6): 16. PROCEDURES AND FUNCTIONS 127 .1 .Standard Procedures 16.3 Crt Init Syntax: Crtlnit Sends the Terminal Initialization String defined in the installation procedure to the screen.2. the following standard procedures are available.2 and 15.7.2 Standard Procedures TURBO Pascal contains a number of standard procedures. 16. Beware that some screens also reset the video-attributes when clearing the screen.5. 14. possibly disturbing any user-set attributes.1 ClrEol Syntax: ClrEol Clears all characters from the cursor position to the end of the line without moving the cursor.5).2 .2.2. procedures for allocation of dynamic variables (described in sections 15.1. and 14.2.2.2.6).2. 16. and input and output procedures (described in section 14.2 CIrScr Syntax: ClrScr Clears the screen and places the cursor in the upper left-hand corner.5 ). provided that the associated commands have been installed for your terminal (see section 1. These are: 1) 2) 3) 4) string handling procedures (described in section 9.2. file handling procedures (described in sections 14.

1).2.2.2.7 Ins line Syntax: I nsLine Inserts an empty line at the cursor position. or row) and Ypos (vertical value.16.4 Crt Exit 16. 16. or column). 128 TURBO Pascal Language Manual . 16. The upper left corner (home position) is (1.2.2. The exact time may vary somewhat in different operating environments.6 Delline Syntax: DelLine Deletes the line containing the cursor and moves all lines below one line up.8 GotoXY Syntax: GotoXY(Xpos.4 Crt Exit Syntax: CrtExit Sends the Terminal Reset String defined in the installation procedure to the screen.2. Ypos) Moves the cursor to the position on the screen specified by the integer expressions Xpos (horizontal value.2.2.5 Delay Syntax: Delay(Time) The Delay procedure creates a loop which runs for approx.2.2. as many milliseconds as defined by its argument Time which must be an integer.2. 16. All lines below are moved one line down and the bottom line scrolls off the screen.2. 16.

Var is variable of any type.2. and Value is an expression of type Byte or Char.LowVideo 16.2.9 16.2. a PROCEDURES AND FUNCTIONS 129 .2. 16. 16. i.e. the 'normal' screen mode. Num bytes.12 Move Syntax: Move(var1.Num} Does a mass copy directly in memory of a specified number of bytes.2. This is because Move automatically handles possible overlap during the move process. var1 and var2 are two variables of any type. Value} Fills a range of memory with a given value. starting at the first byte occupied by Var.10 Norm Video Syntax: NormVideo Sets the screen to the video attribute defined as 'Start of Normal Video' in the installation procedure.e.9 LowVideo Syntax: LowVideo Sets the screen to the video attribute defined as 'Start of Low Video' in the installation procedure. 'dim' characters.2. i. The procedure copies a block of Num bytes.11 Randomize Syntax: Randomize Initializes the random number generator with a random value. 16.2.2. Num is an integer expression.13 Fil/Char Syntax: FiliChar(Var. starting at the first byte occupied by var1 to the block starting at the first byte occupied by var2. and Num is an integer expression.2. are filled with the value Value.var2. You may notice the absence of explicit 'moveright' and 'moveleft' procedures.2.2. 16. Num.2.

a string type. the function will be invoked recursively. If the function designator appears in the statement part of the function itself.1 Function Declaration A function declaration consists of a function heading and a block which is a declaration part followed by a statement part. The statement part of a function is a compound statement as described in section 7. Within the statement part at least one statement assigning a value to the function identifier must occur. This is done by adding a colon and a type to the heading as shown here: function KeyHit: Boolean. function Power(X. functions are either standard (pre-declared) or declared by the programmer.3 Functions 16.e. (CP/M-SO only: Notice that the A compiler directive must be passive {$A-} when recursion is used. Boolean. The declaration part of a function is the same as that of a procedure.3 Functions Like procedures.2.3.Y: Real): Real. Real. Integer. The function heading is equivalent to the procedure heading.16. see appendix E . The last assignment executed determines the result of the function. or a pointer type. 16.1. declared scalar or subrange). function Compute(Var Value: Sample): Real. Char.) 130 TURBO Pascal Language Manual . except that the heading must define the type of the function result. The result type of a function must be a scalar type (i.

The function SimpleRowSum is nested within the function RowSum. Note that the type used in the definition of a function type must be previously specified as a type identifier. begin Read(Number) .Number. The following program is the classical demonstration of the use of a recursive function to calculate the factorial of an integer number: {$A.FactorialCNumber) ). begin RowSum . function FactorialCValue: Integer): Real. Va. . the construct: function LowCase(Line: UserLine): string[80].Function Declaration 16. Instead. end.SimpleRowSum(J) -SimpleRowSum( I -1). end.: type Str80 = string[ 80]. is not allowed.3. Writeln(~M.1 The following example shows the use of a function to compute the sum of a row of integers from I to J.' ! '. end. e.g. Thus. SimpleRowSum is therefore only available within the scope of RowSum. function RowSumCI.J: Integer): Integer. and that type identifier should then be used to define the function result type. begin if Value = 0 then Factorial := 1 else Factorial : = Value * FactorialCvalue-l).r Number: Integer. end. a type identifier should be associated with the type stringf80J. PROCEDURES AND FUNCTIONS 131 . begin SimpleRowSum := S*(S+l) div 2.} program Factorial. function SimpleRowSum(S: Integer): Integer. function LowCase(Line: UserLine): Str80.

1 Arithmetic Functions 16. whose tangent is Num. and its type must be either Real or Integer.3. a function using any of the standard procedures Read.1 ).2.3. The argument Num must be either Real or Integer.1 Function Declaration Because of the implementation of the standard procedures Write and Writeln.1 Abs Syntax: Abs( Num) Returns the absolute value of Num. Readln. 132 TURBO Pascal Language Manual . The result is of type Real.3.2 and 14.3. in radians.3 Cos Syntax: Cos( Num) Returns the cosine of Num. must never be called by an expression within a Write or Writeln statement. 16. 16. file handling functions (described in section 14.1. In 8-bit systems this is also true for the standard procedures Str and Val.2.2 ArcTan Syntax: ArcTan( Num) Returns the angle.5 ).5.2 and 15.1. Write. 16. The argument X must be either Real or Integer.16. and the result is of the same type as the argument. The argument Num is expressed in radians.2.5). or Writeln. and pointer related functions (described in sections 15.2 Standard Functions The following standard (pre-declared) functions are implemented in TURBO Pascal: 1) string handling functions (described in section 9.3. and the result is Real.1.2.3. 2) 3) 16.

The result is of type Real.1.3. and the result is Real. and the result is Real. The argument Num must be either Real or Integer.2. if Num ) = 0. The argument Num must be either Real or Integer.5 Frac Syntax: Frac( Num) Returns the fractional part of Num. and the result is Real.2. 16. i. if Num < O. = 16. and the result is Real.7 Ln Syntax: Ln( Num) Returns the natural logarithm of Num. PROCEDURES AND FUNCTIONS 133 .3. i.3 16.e. The argument Num is ~xpressed in radians.3. 16.1. The argument Num must be either Real or Integer. The argument Num must be either Real or Integer.1. 16.1. enum . the greatest integer number less than or equal to Num.2.e. i.8 Sin Syntax: Sin( Num) Returns the sine of Num.3.6 Int Syntax: Int( Num) Returns the integer part of Num.Int( Num).Cos 16.3. Frac( Num) Num .4 Exp Syntax: Exp( Num) Returns the exponential of Num.2.1.3. and its type must be either Real or Integer.1.2.2.e. or the smallest integer number greater than or equal to Num.

2.2. 16.3.2 Scalar Functions 16. Num is of any scalar type. 134 TURBO Pascal Language Manual .2.1.9 Sqr 16.e.10 Sqrt Syntax: Sqrt( Num) Returns the square root of Num.2.16.2. The argument Num must be either Real or Integer. and the result is Real. The argument Num must be either Real or Integer. Num is of any scalar type.3.2.1. 16. Num must be of type Integer.2 Succ Syntax: Succ( Num) Returns the successor of Num (if it exists).3 Odd Syntax: Odd( Num) Returns boolean True is Num is an odd number.2.3. and False if Num is even.2.2.3. i. 16.1 Pred Syntax: Pred( Num) Returns the predecessor of Num (if it exists).3. 16. Num~ Num.9 Sqr Syntax: Sqr( Num) Returns the square of Num.3.1.3. and the result is of the same type as the argument.2.

3.5). 16. 16. = PROCEDURES AND FUNCTIONS 135 . 16..2. and the result is of type Integer.3 Round Syntax: Round( Num) Returns the value of Num rounded to the nearest integer as follows: if Num > 0.3. Num must be of type Real.3.2. In addition to the following functions.4 Trunc Syntax: Trunc( Num) Returns the greatest integer less than or equal to Num. and the result is of type Integer.2. Example: Chr(65) returns the character 'A'.Num < O. then Round{Num) Trunc{Num + 0. if Num > 0.Transfer Functions 16.2 Ord Syntax: Ord( Var) Returns the ordinal number of the value Var in the set defined by the type Var. = = 16. and if Num <0.3 16. then Round{Num) = Trunc{Num .0.3.3 .3.3. Var may be of any scalar type. or the smallest integer greater than or equal to Num.3. and the result is of type Integer. Ord{Var) is equivalent to Integer{Var) (see Type Conversiions in section 8.3. the retype facility described in section 8. except Real. if.3.2.3 Transfer Functions The transfer functions are used to convert values of one scalar type to that of another scalar type.3 serves this purpose.2.5) Num must be of type Real.3.2.1 Chr Syntax: Chr( Num) Returns the character with the ordinal value given by the integer expression Num.

3. 16.2.2. The high order byte of the result is zero.16.3. The type is Real.2. and False if no key has been pressed. The type of the result is Integer 16.4 Random Syntax: Random Returns a random number greater than or equal to zero and less than one.2.1 Hi Syntax: Hi( t) The low order byte of the result contains the high order byte of the value of the integer expression I.3.4 Miscellaneous Standard Functions 16.4. Num and the random number are both Integers.4.3.3. The type of the result is Integer.3. 16. 136 TURBO Pascal Language Manual .5 Random( N um) Syntax: Random( Num) Returns a random number greater than or equal to zero and less than Num.2 KeyPressed Syntax: KeyPressed Returns boolean True if a key has been pressed at the console. 16.2.4.4.4 Miscellaneous Standard Functions 16.3 Lo Syntax: Lo( t) Returns the low order byte of the value of the integer expression I with the high order byte forced to zero.2.4.3. The result is obtained by calling the operating system console status routine.2.

the argument is returned unchanged.3.4.8 Syntax: UpCase( ch) Returns the uppercase equivalent of its argument ch which must be of type Char.4. The result is of type Integer. 16.Size Of 16.2.6 SizeOf Syntax: SizeOf( Name) Returns the number of bytes occupied in memory by the variable or type Name.4.3.2. If no uppercase equivalent exists. Example: Swap($1234) UpCase returns$3412 (values in hex for clarity).2.2.6 16.3.4.3. 16.7 Swap Syntax: Swap( Num) The Swap function exchanges the high and low order bytes of its integer argument Num and returns the resulting value as an integer. PROCEDURES AND FUNCTIONS 137 .

Write( 'Ok. Writeln(1). I end. 2 <> 0 do begin I := 1*3+1. funct ion Up. end. . Var X: Integer.16. funct ion Up(Var I: Integer): Integer. types. Example: program Catch22. if I <> 1 then I := Up(I). begin Write( 'Enter any integer: .4 Forward References 16. begin while I mod. Program stopped again. except that it is terminated by the reserved word forward. specifying only the name and no parameters. end. Writeln(I). Readln(X).). funct ion Down(Var I: Integer): Integer. When the program is executed and if you enter e. The block follows later within the same declaration part. begin I := I div 2. 6 it outputs: 138 TURBO Pascal Language Manual . Notice that the block is initiated by a copy of the heading. : = Down( 1) . This separate subprogram heading is exactly as the normal heading. etc. X := Up(X).4 Forward References A subprogram is forward declared by specifying its heading separately from the block. end.).g. forward.

X div 2 else X . Write( 'Ok.X*3+1. .4 3 10 5 16 8 4 2 1 Ok. Var X: Integer. Wri te In(X). It may interest you to know that it cannot be proved if this small and very simple program actually will stop for any integer! PROCEDURES AND FUNCTIONS 139 . Program stopped again.Forward References 16.). 2 0 tben X . while X <> 1 do begin if X mod. Program stopped again... end. begin Write( 'Enter any integer: . end.). Readln(X) . The above program is actually a more complicated version of the following program: program Catch222.

4 Forward References Notes: 140 TURBO Pascal Language Manual .16.

Exampes: {$I firs t . begin for I := 1 to Length(St) do St[I] := Up:Jase(St[I]). may be kept as a 'library' of files from which the necessary files can be included in any other program. File STUPCASE. let us assume that in your 'library' of commonly used procedures and functions you have a file called STUPCASE. pas} {$i StdProc} {$I COMPUTE. once tested and debugged. In any future program you write which requires this function to convert strings to upper case letters. Var I: Integer. This directive must be specified on a line by itself. StUp:Jase : = St end. The syntax for the I compiler directive is: {$I f i 1ename } where filename is any legal file name. If no file type is specified. MOD} To demonstrate the use of the include facility.FUN.FUN: function StUp:Jase (St: AnyString): AnyString. you need only include the file at compile-time instead of duplicating it into the source code: INCLUDING FILES 141 . INCLUDING FILES The fact that the TURBO editor performs editing only within memory limits the size of source code handled by the editor. The I compiler directive can be used to circumvent this restriction.PAS is assumed. as it provides the ability to split the source code into smaller 'lumps' and put it back together at compile-time. the default type . as commonly used subprograms. The include facility also aids program clarity.INCLUDING FILES 17 17. Spaces are ignored and lower case letters are translated to upper case. It contains the function StUpCase which is called with a character or a string as parameter and returns the value of this parameter with any lower case letters set to upper case.

i. Notice that TURBO Pascal allows free ordering.e. i. 142 TURBO Pascal Language Manual . it is reset to its original value upon return to the including file. as any change to a 'library' routine will automatically affect all programs including this routine. AnySt ring= string[ 255]. Include files cannot be nested. Compiler directives are described in appendix E . if a compiler directive is set to a different value in an included file. You may thus e. All compiler directives except Band C are local to the file in which they appear.FUN} begin ReadLn(Answer) . Var Answer: InData. it also makes the task of keeping programs updated quicker and safer. of the individual sections of the declaration part. have a number of files containing various commonly used type definitions in your 'library' and include the ones required by different programs.e. type InData= string[ 80] .17 INCLUDING FILES program Inc Iude Demo. one include file cannot include yet another file and then continue processing.g. and even multiple occurrences. Band C directives are always global. This method not only is easier and saves space. Wri te In(StUpCase(Answer)). end. {$I STUPCASE.

A. and H select the compiler mode.T.T Memory / Com file / cHn-file The three commands M. code is produced in memory and resides there ready to be activated by a Run command. technical aspects of the compiler. compile -> Kemory Com. i.CP/M-80 A A. calling machine language routines.e. These are described in section A.fi Ie Find run-time error Quit Figure A-l : Options Menu A. CP/M-80 143 . It also provides a helpful function to find runtime errors in programs compiled into object code files. It presents two kinds of information: 1) Things you must know to make efficient use of TURBO Pascal. CP/M-SO This appendix describes features of TURBO Pascal specific to the 8-bit implementation. Memory is the default mode. e. etc. 2) The remaining sections describe things which are only of interest to experienced programmers.l . where to put the code which results from the compilation. When active.1 compiler Options The 0 command selects the following menu on which you may view and change some default values of the compiler.fi Ie cHn.g. C.

if specified) and the file type . When Com or cHn mode is selected.1.2 and A. The arrow moves to point to this line. 144 TURBO Pascal Language Manual .COM. code is written to a file with the same name as the Work file (or Main file. cHain-file is selected by pressing H. Don't set the Start address to anything less than the minimum value. for absolute variables to be shared by a series of chained programs. you are prompted to enter a new Start address. and may be activated by typing its name at the console.2 Start Address The Start address specifies the address (in hexadecimal) of the first byte of the code. the menu is expanded with the following two lines: Start address: XXXX (min YYYY) End address: XXXX (max YYYY) Figure A-2: Start and End Addresses The use of these additional commands are explained in sections A.A. A. but may be changed to a higher address if you want to set space aside e. as the code will then overwrite part of the Pascal library.1. This file contains the program code but no Pascal library and must be activated from another TURBO Pascal program with the Chain procedure (see section A.1 Memory / Com file / c Hn -file Com-file is selected by pressing C. This file contains the program code and Pascal runtime library. and program code starts at a lower address. This is normally the end address of the Pascal library plus one. code is written to a file with the same name as the Work file (or Main file.3. When you enter an 5.I.CHN.g. When active. the minimum value is assumed. if specified) and the file type . Programs compiled this way may be larger than programs compiled in memory. The arrow moves to point to this line. If you just hit <RETURN>. as the program code itself does not take up memory during compilation.1 0 ). When active.1.

enter the address given by the error message: CP/M-80 145 .e.e.: Run-time error 01. and if you set it higher than the TPA top.4 Find Runtime Error When you run a program compiled in memory. it will be wise to set this value relatively low.CHN file. BOOS minus one.End Address A. the resulting programs cannot be executed from TURBO. When you enter an E. If you anticipate your programs to run on a range of different computers. When prompted for the address. This.l. the default value is assumed (j. A. of course. If compiled programs are to run in a different environment. e. as they will overwrite the TURBO loader. The value in parentheses indicate the top of the TPA on your computer. enter the F command on the Options menu. If you just hit (RETURN). and a runtime error occurs. is not possible if the program is in a . the editor is invoked. PC=IB56 Program aborted Figure A-3: Run-time Error Message To find the place in the source text where the error occurred. e. i. If you set the End address higher than this. you are prompted to enter a End address.g. The default setting is 700 to 1000 bytes less to allow space for the loader which resides just below BOOS when executing programs from TURBO.COM file or an .g.l.l. or even A 100 (40K) if the program is to run under MP/M. and the error is automatically pointed out. C1 00 (48K). top of TPA less 700 to 1000 bytes).3 A. the resulting programs will overwrite part of BOOS if run on your machine.3 End Address The End address specifies the highest address available to the program (in hexadecimal). Run time errors then print out the error code and the value of the program counter at the time of the error. the End address may be changed to suit the TPA size of that system.

Example: var IObyte: Byte absolute $0003.1A Find Runtime Error Ent e r PC:-1B5.A. This is done by adding the reserved word absolute and an address expressed by an integer constant to the variable declaration. StrLen: Byte absolute Str.e. Figure A-4: Find Run-time Error The place in the source text is now found and pointed out exactly as if the error had occurred while running the program in memory.2 Standard Identifiers The following standard identifiers are unique to the CP/M -80 implementation: Bios BiosHL_ Bdos BdosHL RecurPtr StackPtr A. CmdLine: string[127] absolute $80. When absolute is followed by the variable (or parameter) identifier. 146 TURBO Pascal Language Manual . the new variable will start at the address of that variable (or parameter). Example: var Str: string[32]. A.3 Absolute Variables Variables may be declared to reside at specific memory addresses. that a variable should start at the same address as another variable. Absolute may also be used to declare a variable "on top" of another variable. and are then called absolute.Q. i.

the byte at the address specified by the index is used. and if name is a record. Further details on space allocation for variables are given in sections A. called Mem and Port. it may be subscribed. Mem[WsCursor+2] : = Orde' -.4 Addr Function Syntax: Addr{ name) Returns the address in memory of the first byte of the type.1 Mem Array The predeclared array Mem is used to access memory.2.3 The above declaration specifies that the variable StrLen should start at the same address as the variable Str. Mem[WsCursor+l1 := $lB.Absolute Variables A. A. When the Mem array is used in an expression. which are used to directly access CPU memory and data ports. procedure. and since the first byte of a string variable gives the length of the string. variable. ). .1 5 and A. If name is an array.S Predefined Arrays TURBO Pascal offers two predefined arrays of type Byte. Ident2: Integer absolute $8008 is illegal. The value returned is of type Integer. When a value is assigned to a component of Mem. Mem[Addr+Of f set] : = Mem[Addr].1 6 . Each component of the array is a Byte. i. specific fields may be selected. A. CP/M-80 147 . A.5. or function with the identifier name. Notice that only one identifier may be specified in an absolute declaration. IObyte : = Mem[ 3]. Example: Mem[WsCursor] . the construct Identl.e. and indexes correspond to addresses in memory. it is stored at the address given by the index expression. The index type is Integer. StrLen will contain the length of Str.

148 TURBO Pascal Language Manual .8 Pointer Related Items A.e.2 Port Array A. The result is an Integer. For each block. i. as the result is greater than GMaxlnt. but the W direrctive may be used to change this value to between 0 and 9.B. which causes execution speed optimization. When passive. When a component of Port is referenced in an expression. Memory management is discussed in further detail in section A. {$X+l. it is output to the port specified. A. MemAvail returns a negative number. Furthermore.7 With Statements The default 'depth' of nesting of With statements is 2. Keeping the nesting to a minimum may thus greatly afftect the size of the data area in programs with many subprograms. components of Port cannot function as variable parameters to procedures and functions. the index type is Byte. i. its value is input from the port specified. Each element of the array represents a data port with indexes corresponding to port numbers. operations referring to the entire Port array (reference without index) are not allowed. The correct number of free bytes is then calculated as 65536. A. When a value is assigned to a component of Port. {$X-l. With statements require two bytes of storage for each nesting level allowed. The default mode is active. As data ports are selected by 8-bit addresses. The use of the port array is restricted to assignment and reference in expressions only.6 Array Subscript Optimization The X compiler directive allows the programmer to select whether array subscription should be optimized with regard to execution speed or to code size.0 + MemAvail. the code size is minimized.A.e. A.5. and if more than 32767 bytes is available.e.5.16 . Notice the use of a real constant to generate a Real result.2 Port Array The Port array is used to access the data ports of the Z-80 CPU.t MemAvail The standard function MemAvail is available to determine the available space on the heap at any given time. i.

B. or even program code. An external subprogram has no block. however. external $0123 Parameters may be passed to external subprograms. external $lC00.Pointers and Integers A. and the syntax is exactly the same as that of calls to ordinary procedures and functions: procedure Plot(X. If used carelessly. A.B. i. Only the subprogram heading is specified. A. function IOstatus: boolean. external $F003. Parameter passing to external subprograms is discussed further in section A.9 External Subprograms The reserved word external is used to declare external procedures and functions. Ord returns the address contained in its pointer argument as an Integer. procedure QuickSort(var List: PartNo). immediately followed by the reserved word external and an integer constant defining the memory address of the subprogram: procedure DiskReset. as a dynamic variable may be made to overwrite other variables.e.Y: Integer).10 Chain and Execute TURBO Pascal provides two standard procedures: Chain and Execute which allow you to activate other programs from a TURBO program. and Per converts its Integer argument into a pointer which is compatible with all pointer types. typically procedures and functions written in machine code.- 15. they are very dangerous. external $EC00. The syntax of these procedure calls is: Chain(Fi lVar) Execute (Fi lVar) 149 CP/M-BO .3.2 Pointers and Integers The standard functions Ord and Per provide direct control of the address contained in a pointer. no declaration part and no statement part.2 A. These functions are extremely valuable in the hands of an experienced programmer as they allow a pointer to point to anywhere in memory.

1 ).e. an I/O error occurs. It is loaded into memory and executed at the start address of the current program.A. the address specified when the current program was compiled. When these conditions are satisfied. Furthermore. no Pascal library. both programs must be compiled to the same memory size (see section A.3 ).e.e. This could be a file created by TURBO Pascal with the Com-option selected on the Options menu (see section A. and the IOresult function must be called prior to further I/O. the variables will be placed at the same address in memory by both programs. and they must be listed in the same order in both declarations. i. The file is loaded and executed at address $1 00. the current program and the chained program must use the same start address. 150 TURBO Pascal Language Manual . To insure overlapping. Such a file contains only program code. it is loaded into memory and executed. any file containing executable code. If the disk file does not exist.8 . If the file exists.COM file. This error is treated as descri-bed in section 14. It then uses the Pascal library already present in memory. i.1. files compiled with the cH n-file option selected on the Options menu (see section A. The Execute procedure may be used to execute any . Thus.CHN files.10 Chain and Execute where FilVar is a file variable of any type. previously assigned to a disk file with the standard procedure Assign. If the I compiler directive is passive ({ $I-}). The Chain procedure is used only to activate special TURBO Pascal .1. shared global variables should be declared as the very first variables in both programs.1. as specified by the CP/M standard. program execution continues with the statement following the failed Chain or Execute statement. they may be shared. i.1 ). Data can be transferred from the current program to the chained program either by shared global variables or by absolute address variables. and as TURBO Pascal does not automatically initialize its variables.

otherwise it was activated from the operating system. as the $FF value in address $80 may otherwise cause confusion. Txt: CntPrg: file. Program CHRCOUNT.Chain and Execute A. for I := 1 to length(Txt) do if Txt [I] in [ 'A' . NoOfChar. i. var string[ 80] . Writeln( '. from a program run with the compiler options switch in position Memory (section A. As s i gn( CntPrg. var Txt: string[ 80] .NoOfChar). A program can determine whether it was invoked by Chain or Execute byexamining the value of the byte at address $80 (which normally contains the length of the CP/M command line). If this byte is $FF (255). . Care should be taken if executing non-TURBO programs that they do not use the CP/M command line when invoked. .10 Example: Program MAIN. chn' ) . NoOfUpc.). Note that neither Chain nor Execute can be used in direct mode. COM: program Main. 'Z'] tben NoOfUpc . begin NoOfUpc .). 'ChrCount .0. Chain(CntPrg) . end. CP/M-80 151 . '. . the program was activated by Chain or Execute. No of upper case characters: " NoOfUpc. I: Integer.1 ). Readln(Txt). N00 fChar : = Lengt h( Txt) . Wri tee 'No of characters in entry: '.e.CHN: program ChrCount. begin Wri tee 'Enter any text: ..Succ(NoOfUpc).1. end.

optionally followed by an offset consisting of a plus or a minus sign and an integer constant.11 In-line Machine Code TURBO Pascal features the inline statements as a very convenient way of inserting machine code instructions directly into the program text. it is added or subtracted before coding the address. variable identifiers. An asterisk alone generates two bytes of code (in byte reversed format) containing the current location counter value. $FF). and they must be of type Integer. Literals generate one byte of code if within the range 0 .L1 20H (HL) . An inline statement consists of the reset:Ved word inline followed by one or more constants. (HL) B B Z. (HL) 'a' C. If the asterisk is followed by an offset.L2 HL A. The following example of an inline statement generates machine code that will convert all characters in its string argument to upper case.11 In -line Machine Code A. The constants may be either literal constants or constant identifiers. A variable identifier generates two bytes of code (in byte reversed format) containing the memory address of the variable.A. end.L1 } } } } } } } } } } } } } } } DED JP INC LD CF JP CF JP SUB LD JP $CA!*+20/ $23/ $7E/ $FE/$61/ $DAi*-9/ $FE/$7B/ $02/*-14/ $06/$20/ $77/ $03/*-20). procedure UpperCase(va. 255 ($00 . separated by slashes and enclosed in parentheses..A L1 EXtU $ 152 TURBO Pascal Language Manual . { { { { { { { { { { { L2: 'z'+l NC. or location counter references. begin { inline ($2AjStrg/ { $46/ { $04/ { Ll: $05/ {Str is type String[255] } LD LD INC HL. otherwise two bytes in the standard byte reversed format. A location counter reference consists of an asterisk. (Strg) B.r Strg: Str).. Constant identifiers always generate two bytes of code.

A. TURBO Pascal introduces two standard procedures: Bdos and Bios. and four standard functions: Bdos. and inline statements may use all CPU registers. Param is optional and denotes a parameter which is loaded into the DE register pair. Details on BOOS and BIOS routines are found in the CP/M Operating System Manual published by Digital Research. Func and Param are integer expressions. A call to address 5 then invokes the BOOS.1 Bdos procedure and function Syntax: Bdos( Func {. A.12 CP/M Function Calls For the purpose of calling CP/M BOOS and BIOS routines. CP/M-80 153 .12.11 Inline statements may be freely mixed with other statements throughout the statement part of a block. Func denotes the number of the called routine and is loaded into the C register. BdosHL.In -line Machine Code A. Bios. Param } ) The Bdos procedure is used to invoke CP/M BOOS routines. however. and BiosHL. Param } ) This function is exactly similar to the Bdos function above. The Bdos function is called like the procedure and returns an Integer result which is the value returned by the BOOS in the A register.2 BdosHL function Syntax: BdosHL( Func {.1 2. except that the result is the value returned in the H L register pair. Note. that the contents of the stack pointer register (SP) must be the same on exit as on entry. A.

A.T 2.3

Bios procedure and function

A.1 2.3

Bios procedure and function

Syntax: 8 ios(Func {, Param } ) The Bios procedure is used to invoke 810S routines. Func and Param are integer expressions. Func denotes the number of the called routine, with 0 meaning the W800T routine, 1 the CONST routine, etc. I.e. the address of the called routine is Func 3 plus the W800T address contained in addresses 1 and 2. Param is optional and denotes a parameter which is loaded into the 8C register pair prior to the call.

*

The Bios function is called like the procedure and returns an integer result which is the value returned by the 8 lOS in the A register.

A.12.4

BiosHL function

Syntax: 8iosHL(Func (, Param }) This function is exactly similar to the Bios function above, except that the result is the value returned in the HL register pair.

154

TURBO Pascal Language Manual

User Written I/O Drivers

A.13

A.13

User Written I/O Drivers

For some applications it is practical for a programmer to define his own input and output drivers, i.e. routines which perform input and output of characters to and from external devices. The following drivers are part of the TURBO environment, and used by the standard I/O drivers (although they are not available as standard procedures or functions):
function ConSt: boolean; function Conln: Char; procedure ConOut(Ch: Char); procedure LstOut(Ch: Char); procedureAuxOut(Ch: Char); function Auxin : Char; procedure UsrOut(Ch: Char); function Usrln: Char;

The ConSt routine is called by the function KeyPressed, the Conln and ConOut routines are used by the CON:, TRM:, and KBD: devices, the LstOut routine is used by the LST: device, the AuxOut and Auxin routines are used by the AUX: device, and the UsrOut and Usrln routines are used by the USR: device. By default, these drivers use the corresponding BIOS entry points of the CP/M operating system, i.e. ConSt uses CONST, Conln uses CONIN, ConOut uses CONOUT, LstOut uses LIST, AuxOut uses PUNCH, Auxin uses READER, UsrOut uses CONOUT, and Usrln uses CONIN. This, however, may be changed by the programmer by assigning the address of a self-defined driver procedure or a driver function to one of the following standard variables:
Variable Contains the address of the

ConStPtr ConlnPtr ConOutPtr LstOutPtr AuxOutPtr AuxlnPtr UsrOutPtr UsrlnPtr

ConSt function Conln function Con Out procedure LstOut procedure AuxOut procedure Auxin function UsrOut procedure Usrln function

A user defined driver procedure or driver function must match the definitions given above, i.e. a ConSt driver must be a Boolean function, a Conln driver must be a Char function, etc.

CP/M-80

155

A.14

Interrupt Handling

A.14

Interrupt Handling

The TURBO Pascal run time package and the code generated by the compiler are both fully interruptible. Interrupt service routines must preserve all registers used. If required, interrupt service procedures may be written in Pascal. Such procedures should always be compiled with the A compiler directive active ({$A+})' they must not have parameters, and they must themselves insure that all registers used are preserved. This is done by placing an inline statement with the necessary PUSH instructions at the very beginning of the procedure, and another inline statement with the corresponding POP instructions at the very end of the procedure. The last instruction of the ending inline statement should be an EI instruction ($FB) to enable further interrupts. If daisy chained interrupts are used, the inline statement may also specify a RETI instruction ( $EO, $40), which will override the RET instruction generated by the compiler. The general rules for register usage are that integer operations use only the AF, BC, DE, and HL registers, other operations may use IX and IY, and real operations use the alternate registers. An interrupt service procedure should not employ any I/O operations using the standard procedures and functions of TURBO Pascal, as these routines are not re-entrant. Also note that BOOS calls (and in some instances BIOS calls, depending on the specific CP/M implementation) should not be performed from interrupt handlers, as these routines are not re-entrant. The programmer may disable and enable interrupts throughout a program using 01 and EI instructions generated by inline statements. If mode 0 (1M 0) or mode 1 (1M 1) interrupts are employed, it is the responsibility of the programmer to initialize the restart locations in the base page (note that RST 0 cannot be used, as CP/M uses locations 0 through 7). If mode 2 (1M 2) interrupts are employed, the programmer should generate an initialized jump table (an array of integers) at an absolute address, and initialize the I register through a inline statement at the beginning of the program.

156

TURBO Pascal Language Manual

Internal Data Formats

A.15

A.15

I nternal Data Formats

In the following descriptions, the symbol @ denotes the address of the first byte occupied by a variable of the given type. The standard function Addr may be used to obtain this value for any variable.

A.15.1

Basic Data Types

The basic data types may be grouped into structures (arrays, records, and disk files), but this structuring will not affect their internal formats.

A.15.T.T

Scalars

The following scalars are all stored in a single byte: Integer subranges with both bounds in the range 0 .. 255, Booleans, Chars, and declared scalars with less than 256 possible values. This byte contains the ordinal value of the variable. The following scalars are all stored in two bytes: Integers, Integer subranges with one or both bounds not within the range 0 .. 255, and declared scalars with more than 256 possible values. These bytes contain a 2's complement 16-bit value with the least significant byte stored first.

A.15.T.2

Reals

Reals occupy 6 bytes, giving a floating point value with a 40-bit mantissa and an 8-bit 2's exponent. The exponent is stored in the first byte and the mantissa in the next five bytes which the least significant byte first:

@
@+1 @ +5

Exponent LSB of mantissa MSB of mantissa

The exponent uses binary format with an offset of $80. Hence, an exponent of $84 indicates that the value of the mantissa is to be multiplied by 2 ($84$80) = 2 4 = 16. If the exponent is zero, the floating point value is considered to be zero.
ft ft

CP/M-80

157

A.15.1.2

Reals

The value of the mantissa is obtained by dividing the 40-bit unsigned integer by 2 40. The mantissa is always normalized, i.e. the most significant bit (bit 7 of the fifth byte) should be interpreted as a 1. The sign of the mantissa is stored in this bit, a 1 indicating that the number is negative, and a 0 indicating that the number is positive.
A

A.15.1.3

Strings

A string occupies the number of bytes corresponding to one plus the maximum length of the string. The first byte contains the current length of the string. The following bytes contain the actual characters, with the first character stored at the lowest address. In the table shown below, L denotes the current length of the string, and Max denotes the maximum length:
@

+1 @+2
@ @ @

Current length (L) First character Second character Last character Unused Unused

+L +L+1

@+Max

A.15.1.4

Sets

An element in a set occupies one bit, and as the maximum number of elements in a set is 256, a set variable will never occupy more than 32 bytes (256/8). If a set contains less than 256 elements, some of the bits are bound to be zero at all times and need therefore not be stored. In terms of memory efficiency, the best way to store a set variable of a given type would then be to "cut off" all insignificant bits, and rotate the remaining bits so that the first element of the set would occupy the first bit of the first byte. Such rotate operations, however, are quite slow, and TURBO therefore employs a compromise: Only bytes which are statically zero (Le. by'tes of which no bits are used) are not stored. This method of compression is very fast and in most cases as memory efficient as the rotation method.

158

TURBO Pascal Language Manual

Sets A. A. The sector buffer is used to buffer input and output from and to the disk file. The table below shows the format of an FIB: @ @ +1 @+2 @+3 @+4 @+5 @+6 @+7 @+8 @+9 @ +10 @+11 @ +12 @ +47 @+48 @ +175 Flags byte File type Character buffer Sector buffer pointer Number of records (LSB) Number of records (MSB) Record length in bytes (LSB) Record length in bytes (MSB) Current record number (LSB) Current record number (MSB) Unused (reserved) Unused (reserved) First byte of CP/M FCB Last byte of CP/M FCB First byte of sector buffer Last byte of sector buffer CP/M-80 159 . An FIB occupies 176 bytes of memory and is divided into two sections: The control section (the first 48 bytes).1. and the sector buffer (the last 128 bytes). The control section contains various information on the disk file or device currently assigned to the file.(Min div 8) and the bit address within the byte at MemAddress is: BitAddress = E mod 8 where E denotes the ordinal value of the element.4 The number of bytes occupied by a set variable is calculated as (Max div 8) (Min div 8) + 1. The memory address of a specific element E is: MemAddress = @ + (E div 8) .15. where Max and Min are the upper and lower bounds of the base type of that set.5 File Interface Blocks Each file variable in a program has an associated file interface block (FIB).15.1.

the length of the FIB of an untyped file is only 48 bytes. Bytes@ +10 and@ +11 are currently unused. as data is transferred directly between a variable and the disk file. The value nil corresponds to a zero word.6 Pointers A pointer consists of two bytes containing a 16-bit memory address. A. High if data has been written to the sector buffer.A. High if input is allowed. Each field consists of two bytes in byte reversed format.e. Read semaphore. Bytes@ +12 through@ +47 contain a CP/M file control block (FCB). the least significant byte is stored first. but reserved for future expansion. Write semaphore. The following values can occur: o 1 2 3 4 5 6 The console device (CON:) The terminal device (TRM:) The keyboard device (KBD:) The list device (LST:) The auxiliary device (AUX:) The user device (USR:) A disk file When a file is assigned to a logical device. The file type field at@ +1 specifies the type of device currently assigned to the file variable. The following three fields are used only by random access files (defined files) and untyped files.15. The sector buffer pointer at@ +3 contains an offset from the first byte of the sector buffer. 160 TURBO Pascal Language Manual . High if the contents of the sector buffer is undefined.5 File Interface Blocks The flags byte at @ contains four one bit flags which indicate the current status of the file: bit 0 bit 1 bit 2 bit 3 Input flag. The last block of the FIB is the sector buffer used for buffering input and output from and to disk files.1. High if output is allowed.1S. Thus. i. The FIB format described above applies to all defined files and textfiles. and it is stored in memory using byte reversed format. only the first three bytes of the FIB are of significance.1. The FIB of an untyped file has no sector buffer. Output flag.

e.11 Board!1.2.g. 8.15.15.1 Arrays The components with the lowest index values are stored at the lowest memory address. CP/M-80 161 .2 Data Structures Data structures are built from the basic data types using various structuring methods.. If a record contains a variant. Each variant starts at the same memory address.21 Board!1.2 Records The first field of a record is stored at the lowest memory address. given the array Board: arr~[I .21 Highest address: Board!8.1 .2 A. the length is given by the sum of the lengths of the individual fields. A multi-dimensional array is stored with the rightmost dimension increasing first. A. records..Data Structures A.81 Board!2.2. 8] of Square you have the following memory layout of its components: lowest address: Board!1.11 Board!2.15.15. The structuring of data does not in any way affect the internal formats of the basic data types. Three different structuring methods exist: arrays. and disk files. the total number of bytes occupied by the record is given by the length of the fixed part plus the length of largest of its variant parts.81 A. If the record contains no variant parts.

A. Normally.15.3 Disk Files A. sector 0. A. if the programmer wishes to use external subprograms. However.2.3.2. but a text file is subdivided into lines.1 Random Access Files A random access file consists of a sequence of records.2. and POP them at the beginning of the subprogram.2 Text Files The basic components of a text file are characters.15. A disk file is controlled through a file interface block (FIB) as described in section A.15. The first record of the file is stored starting at the fourth byte. byte byte byte byte 0: 1: 2: 3: Number of records (LSB) Number of records (MSB) Record length (LSB) Record length (MSB) A. this is of no interest to the programmer.2.15.3.3 Disk Files Disk files are different from other data structures in that data is not stored in internal memory but in a file on an external device. as the machine code generated by TURBO Pascal will automatically PUSH parameters onto the stack before a call. all of the same length and same internal format. The file is terminated by a Ctrl-Z (ASCII $1 B). sector 0.1. 162 TURBO Pascal Language Manual . the records of a file are totally contiguous.15. Each line consists of any number of characters ended by a CR/LF sequence (ASCII $OD/$OA). sector 0. A. these must POP the parameters from the stack themselves. sector 0. The first four bytes of the first sector of a file contains the number of records in the file and the length of each record in bytes. To optimize file storage capacity.5.15. In general there are two different types of disk files: random access files and text files.3 Parameters Parameters are transferred to procedures and functions via the Z-80 stack.

at higher addresses on the stack. A. CP/M-80 163 . all scalars except Reals) are transferred on the stack as a word. the data transferred on the stack depends upon the type of the parameter as described in the following sections. are located below the return address. A. If the variable occupies only one byte when it is stored.15.15.1S.Parameters A. Chars and declared scalars (i. a word is transferred on the stack giving the absolute memory address of the first byte occupied by the actual parameter. the most significant byte of the parameter is zero. C the second byte.e. and B the first (most significant) byte. the subroutine must first POP off the return address. to access the parameters.3. A. the top of the stack always contains the return address (a word).3. Booleans.e.2 Value Parameters With value parameters. The parameters.2 Reals A real is transferred on the stack using six bytes. H the fifth (least significant) byte of the mantissa .2. A. i.1 Variable Parameters With a variable (VAR) parameter.1S. E the fourth byte. a word is POPped off the stack using an instruction like POP HL. Normally.3. 0 the third byte. if any.2. If these bytes are POPped using the instruction sequence: IDP IDP IDP HL DE BC then L will contain the exponent. then all the parameters. and finally it must restore the return address by PUSHing it back onto the stack. Therefore.15.1 Scalars Integers.3 On entry to an external subroutine.3.

2.3.SP C.StrBuf HL.0 HL.0 B.1S.3.1S.HL This will store the least significant byte of the set at the lowest address in SetBuf A. The bytes at addresses SP+1 through SP+n (where n is the length of the string) contain the string with the first character stored at the lowest address.3. The following machine code instructions may be used to POP the string at the top of the stack and store it in StrBuf ill ill ill ADD ill INC illIR ill DE.4 Sets A set always occupies 32 bytes on the stack (set compression only applies to the loading and storing of sets).3 Strings A.2.HL A.3.A.2.32 SP.SP 00. SetBuf HL.S Pointers A pointer value is transferred on the stack as a word containin the memory address of a dynamic variable. 164 TURBO Pascal Language Manual .H HL.1S. the byte pointed to by SP contains the length of the string.3 Strings When a string is at the top of the stack.2. The following machine code instructions may be used to POP the set at the top of the stack and store it in SetBuf ill ill ADD ill illIR ill DE.15. (HL) 00 SP. The value NIL corresponds to a zero word.

E.2.15.3. and HL register pairs.2. and L must contain the exponent. Strings and sets must be returned on the top of the stack on the formats described in sections A.1 5. except Reals.2. Reals must be returned in the BC.3. C. Instead.4.4 Function Results User written external functions must return their results exactly as specified in the following: Values of scalar types.1S.2. A.6 A. and use it as the source address in a block copy operation.3. 0.1 5.3.6 Arrays and Records Even when used as value parameters.Arrays and Records A. then it must be returned in L and H must by zero. Pointer values must be returned in the HL register pair.3 and A. B.15. CP/M-80 165 . must be returned in the H L register pair. Array and Record parameters are not actually PUSHed onto the stack. It is then the responsibility of the subroutine to POP this word. and H must contain the mantissa (most significant byte in B). DE. a word containing the address of the first byte of the parameter is transferred. If the type of the result is expressed in one byte.

Solid lines indicate fixed boundaries (i.). A. determined by amount of memory.... by the size of the source text. editor...1 Compilation in Memory During compilation of a program in memory (Memory-mode on compiler Options menu....-- Error messages. size of your CP/M.- .A....---...- ~ Object code growing upward i i Symbol table growing downward CPU stack growing downward CP/M HighMem Figure A-5: Memory map during compilation in memorv 166 TURBO Pascal Language Manual .... see section A.. etc. the memory is mapped as follows: 0000 CP/M and run-time workspace Pascal Library Turbo interface. and by possible user manipulation of various pointers..-.-.16 Memory Management A..1..... version of TURBO..).. etc.1 6 Memory Management A.. and compiler .16...16.1 Memory Maps The following diagrams illustrate the contents of memory at different stages of working with the TURBO system. optional Source text . whereas dotted lines indicate boundaries which are determined at runtime (e.1 ). The sizes of the segments in the diagrams do not necessarily reflect the amounts of memory actually consumed...g.-.-...- .e.

16. optional Source text i 1 Symbol table growing downward CPU stack growing downward CP/M HighMem Figure A-6: Memory map during compilation to a file CP/M-80 167 .1. Also. see section A.16. The CPU stack works downwards from the logical top of memory.1 If the error message file is not loaded when starting TURBO.2 Compilation To Disk During compilation to a . it generates object code working upwards from the end of the source text. Compilation of much larger 'programs is thus possible in this mode. and compiler Error messages.1 ). A. the code starts at a lower address (right after the Pascal library instead of after the source text). When the compiler is invoked.Compilation in Memory A. the source text starts that much lower in memory. and the compiler's symbol table works downwards from an address 1 K ($400 bytes) below the logical top of memory. editor.CHN file (Com-mode or cHn-mode on compiler Options menu. the memory looks much as during compilation in memory (see preceding section) except that generated object code does not reside in memory but is written to a disk file.1.COM or . 0000 CP/M and run-time workspace Pascal Library Turbo interface.

the memory is mapped as follows: 0000 CP/M and run-time workspace Pascal Library Turbo interface. optional I.1.--- Object code . see section A.A.1 ). the end of the object code is known..- Source text t..Recursion stack growing downward Default initial value of RecurPtr CPU stack growing downward '.___________ __ J__ _ Default initial state of StackPtr - - .... and compiler Error messages.- Default initial value of HeapPtr Heap growing upward i . 168 TURBO Pascal Language Manual . the Memorymode on compiler Options menu is selected.. The CPU stack grows downwards from here towards the position of the recursion stack pointer RecurPtr.16....- . and the heap grows from here and upwards in memory towards the recursion stack.16..e.-.______ .-. editor.-.. The heap pointer HeapPtr is set to this value by default.-- - -- .[ ..- - .-. Program variables are stored from this address and downwards..- -. $400 bytes lower than StackPtr.3 Execution in Memory When a program is executed in direct . The end of the variables is the 'top of free memory' which is the initial value of the CPU stack pointer StackPtr..1. The recursion stack grows from here downward towards the heap. The maximum memory size is B DOS minus one (indicated on the compiler Options menu).- - -- ..- -- .mode (i.or memory ..-- Program variables CP/M HighMem Figure A-7: Memory map during execution in direct mode When a program is compiled...3 Execution in Memory A.

editor...16. the memory is mapped as follows: 0000 CP/M and run-time workspace Pascal Library Default program start address Object code - - - - -.------------------Loader Default end address Maximum memory size CP/M HighMem Figure A-8: Memory map during execution of a program file This map resembles the previous.. e. by an eXecute command. and compiler (and possible error messages) and of the source text.1. except for the absence of the TURBO interface.-- Default initial value of HeapPtr Heap growing upward --------------- ___ 1__ Recursion stack growing downward Default initial value of RecurPtr ____1___ Default initial state of StackPtr Program variables CPU stack growing downward ------. and the default value is determined by the BDOS location on the computer in use. CP/M-80 169 .1. The maximum memory size is BOOS minus one..4 Execution of A Program File When a program file is executed (either by the Run command with the Comfile mode on the compiler Options menu selected..16. or directly from CP/M).-..Execution of A Program File A.g. The default program start address (shown on the compiler Options menu) is the first free byte after the Pascal runtime library. This value may be manipulated with the Start address command of the compiler Options menu.4 A. to create space for absolute variables and/or external procedures between the library and the code.

4 Execution of A Program File If programs are to be translated for other systems. and The CPU stack pointer allow the programmer to control the position of the heap and the stacks.16. This is to allow space for the loader which resides just below BOOS when .e the first free byte after the object code. The maximum memory may be manipulated with the End address command of the compiler Options menu. On entry to a recursive subprogram it copies its workspace onto the recursion stack. and the recursion stack. A. and possible error messages when the program finishes and thus returns control to the TURBO system. 170 TURBO Pascall. An active for statement also uses the CPU stack. the CPU stack pointer StackPtr is set to the address of the top of free memory. At the beginning of a program. Notice that the default end address setting is approx. This loader restores the TU RBO editor.£nguage Manual . The recursion stack pointer. 700 to 1000 bytes lower than maximum memory. i. The pre-defined variables: HeapPtr: RecurPtr: StackPtr: The heap pointer. The default initial value of RecurPtr at the beginning of a program.. procedures and functions compiled with the A compiler directive passive (~A-}). The heap is used to store dynamic variables. At the beginning of a program.2 The Heap and The Stacks As indicated by the memory maps in previous sections. three stack-like structures are maintained during execution of a program: The heap. Mark. The recursion stack is used only by recursive procedures and functions. variables local to a subprogram must not be used as var parameters in recursive calls. and Release. compiler. The CPU stack is used to store intermediate results during evaluation of expressions and to transfer parameters to procedures and functions.A. Because of this technique. and occupies one word. the heap pointer HeapPtr is set to the address of the bottom of free memory.e. and is controlled with the standard procedures New.COMfiles are Run or eXecuted from the TURBO system. care should be taken to avoid collision with the B ~OS. is 1 K ($400) bytes below the CPU stack pointer.1. i.16. and on exit the entire workspace is restored to its original state. the CPU stack.

The Heap and The Stacks

A.16.2

The type of these variables is Integer. Notice that HeapPtr and RecurPtr may be used in the same context as any other Integer variable, whereas StackPtr may only be used in assignments and expressions. When these variables are manipulated, always make sure that they point to addresses within free memory, and that:
HeapPtr

<RecurPtr <StackPtr

Failure to adhere to these rules will cause unpredictable, perhaps fatal, results. Needless to say, assignments to the heap and stack pointers must never occur once the stacks or the heap are in use. On each call to the procedure New and on entering a recursive procedure or function, the system checks for collision between the heap and the recursion stack, i.e. checks if HeapPtr is less than RecurPtr. If not. a collision has occurred, which results in an execution error. Note that no checks are made at any time to insure that the CPU stack does not overflow into the bottom of the recursion stack. For this to happen, a recursive subroutine must call itself some 300-400 times, which must be considered a rare situation. If, however, a program requires such nesting, the following statement executed at the beginning of the program block will move the recursion stack pointer downwards to create a larger CPU stack:

RecurPtr := StackPtr -2 *MaXDepth -512;
where MaxDepth is the maximum required depth of calls to the recursive subprogram(s). The extra approx. 512 bytes are needed as a margin to make room for parameter transfers and intermediate results during the evaluation of expressions.

CP/M-80

171

A.16.2

The Heap and The Stacks

Notes:

172

TURBO Pascal Language Manual

MS-DOS/PC-DOS and CP/M-86

B

B.

MS-DOS/PC-DOS and CP/M-a6

This appendix describes features of TU RBO pascal specific to the various 16bit implementations. The appendix has three sub-sections: Common features which deals with information common to the MSDOS/PC-DOS and the CP/M -86 implementations. The MS-DOS/PC-DOS implementation which deals with information specific to the MS-DOS implementation. The CP/M -86 implementation which deals with information specific to the CP/M-86 implementation.

B.1

Common features

This section presents two kinds of information: 1) Things you must know to make efficient use of TURBO Pascal. These are described in section B.1.1 . 2) The remaining sections describe things which are only of interest to experienced programmers, e.g. calling machine language routines, technical aspects of the compiler, etc.

8.1.1

Compiler Options

The 0 command selects the following menu from which you may view and change some default values of the compiler. It also provides a helpful function to find runtime errors in programs compiled into object code files.

compile ->

~mory

Com- file cHn- file Find run-time error Quit

Figure B-1: Options Menu

MS-DOS/PC-DOS and CP/M-86

173

B.l.l

Compiler Options

The only difference between the two implementations is that then command Com-file is called Cmd-file in the CP/M-86 implementation.

B.l.l.l

Memory / Com file / cHn -file

The three commands M, C, and H select the compiler mode, i.e. where to put the code which results from the compilation. Memory is the default mode. When active, code is produced in memory and resides there ready to be activated by a Run command. Com-file is selected by pressing C. The arrow moves to point to this line. The compiler writes code to a file with the same name as the Work file (or Main file, if specified) and the file type .COM (in CP/M-86 the file type is .CMD). This file contains the program code and Pascal runtime library, and may be activated by typing its name at the console. cH ain-file is selected by pressing H. The arrow moves to point to this line. The compiler writes code to a file with the same name as the Work file (or Main file, if specified) and the file type .CHN. This file contains the program code but no Pascal library and must be activated from another TURBO Pascal program with the Chain procedure (see section B.1.9 ). When the Com or cH n mode is selected, four additional lines will appear on the screen:

mi ni mum minimum mInimum mAximum

cOde Data free free

segment segment dynamic dynamic

size: size: memory: memory:

XXXX XXXX XXXX XXXX

paragraphs (max. paragraphs (max. paragraphs paragraphs

yyyy) yyyy)

Figure B-2: Memory Usage Menu The use of these commands are described in the following sections.

174

TURBO Pascal Language Manual

Minimum Code Segment Size

8.1.1.2

8.1.1.2

Minimum Code Segment Size

The O-command is used to set the minimum size of the code segment for a .COM using Chain or Execute. As discussed in section B.1.9 , Chain and Execute do not change the base addresses of the code, data, and stack segments, and a 'root' program using Chain or Execute must therefore allocate segments of sufficient size to accommodate the largest segments in any Chained or Executed program. Consequently, when compiling a 'root' program, you must set the value of the Minimum Code Segment Size to at least the same value as the largest code segment size of the programs to be chained/executed from that root. The required values are obtained from the status printout terminating any compilation. The values are in hexadecimal and specify number of paragraphs, a paragraph being 16 bytes.

8.1.1.3

Minimum Data Segment Size

The D-command is used to set the minimum size of the data segment for a .COM using Chain or Execute. As discussed above, a 'root' program using these commands must allocate segments of sufficient size to accommodate the largest data of any Chained or Executed program. Consequently, when compiling a 'root' program, you must set the value of the Minimum Data Segment Size to at least the same value as the largest data segment size of the programs to be chained/executed from that root. The required values are obtained from the status printout terminating any compilation. The values are in hexadecimal and specify number of paragraphs, a paragraph being 16 bytes.

8.1.1.4

Minimum Free Dynamic Memory

This value specifies the minimum memory size required for stack and heap. The value is in hexadecimal and specifies a number of paragraphs, a paragraph being 16 bytes.

MS-DOS/PC-DOS and CP/M-86

175

is not possible if the program is in a .5 Maximum Free Dynamic Memory This value specifies the maximum memory size allocated for stack and heap.1. the editor is invoked.: Run-time error 01. and a runtime error occurs.B. of course.5 Maximum Free Dynamic Memory B. This.Q Figure B -4: Find Run-time Error The place in the source text is now found and pointed out exactly as if the error had occurred while running the program in memory. e.1.1. Run time errors then print out the error code and the value of the program counter at the time of the error. The value is in hexadecimal and specifies a number of paragraphs.1. 176 TURBO Pascal Language Manual .CMD file or an .1.---1OO. enter the F command. PC=1B56 Program aborted Figure B-3: Run-time Error Message To find the place in the source text where the error occurred.CHN file. It must be used in programs which operate in a multi-user environment like Concurrent CP/M -86 to assure that the program does not allocate the entire free memory. B. and the error is automatically pointed out. When prompted for the address. enter the address given by the error message: Ent e r PC.6 Find Runtime Error When you run a program compiled in memory. a paragraph being 16 bytes.COM/.1.g.

MS-DOS/PC-OOS and CP/M-86 177 . The first constant specifies the segment base address. Absolute may also be used to declare a variable "on top" of another variable. Further details on space allocation for variables are found in section B. This declaration specifies that the variable StrLen should start at the same address as the variable Str. and the second constant specifies the offset within that segment. i.e. and as the first byte of a string variable contains the length of the string.12 . StrLen will contain the length of Str.3 Absolute Variables Variables may be declared to reside at specific memory addresses. StrLen: Byte absolute Str.1. the new variable will start at the address of that variable (or parameter).1. When absolute is followed by the variable (or parameter) identifier. Notice that an absolute variable declaration may only specify one identifier. The standard identifiers CSeg and OSeg may be used to place variables at absolute addresses within the code segment (C5eg) or the data segment (05eg): Special: arr~[l .1.2 8.Standard Identifiers 8. and are then called absolute.. Example: var St r: string[ 32].1. CodeSize] absolute CSeg:$05F3. This is done by adding to the variable declaration the reserved word absolute followed by two Integer constants specifying a segment and an offset at which the variable is to be located: var Abc: Integer absolute $0000: $08EE.2 Standard Identifiers The following standard identifiers are unique to the 16-bit implementation: CSeg DSeg Intr MemW Ofs PortW Seg SSeg 8. Def: Integer absolute $0000:$00F0. that a variable should start at the same address as another variable.

and if Name is a record. The value returned is an Integer. it may be subscribed. procedure or function with the identifier Name. it may be subscribed.l.2 afs Syntax: Ofs(Name) Returns the offset in the segment of memory occupied by the first byte of the variable.4 Absolute Address Functions B.B.1.1.1. and if Name is a record.4 Cseg Syntax: Cseg Returns the base address of the Code segment. B. If Name is an array.4.4. If Name is an array. The value returned is an Integer.4 Absolute Address Functions The following functions are provided for obtaining information about program variable addresses and system pointers. 178 TURBO Pascal Language Manual .l.3 Seg Syntax: Seg(Name) Returns the address of the segment containing the first byte of the variable.4. it may be subscribed. and if Name is a record. The value returned is a 32 bit pointer consisting of a segment address and an offset. The value returned is an Integer. 8. procedure or function with the identifier Name.4.1 Addr Syntax: Addr(Name) Returns the address in memory of the first byte of the variable with the identifier Name. If Name is an array. specific fields may be selected. specific fields may be selected. 8. B. specific fields may be selected.1.

1. While the following statement: Merrm[Seg(Var) :Ofs(Var)] :=Value. The value returned is an Integer.6 Sseg Syntax: Sseg Returns the base address of the Stack segment.Dseg B.5 Predefined Arrays TURBO Pascal offers four predefined arrays of type Byte.5 8.1 Mem Array The predefined arrays Mem and Mem Ware used to access memory.1. The following statement assigns the value of the byte located in segment 0000 at offset $0081 to the variable Value Va 1ue : =Mem[ 0080 : $0081] . 8. B.1.4.4.5. Each component of the array Mem is a byte. and each component of the array Wmem is a word (two bytes. Port and PortW which are used to access CPU memory and data ports. 8. LSB first). places the value of the Integer variable Value in the memory location occupied by the two first bytes of the variable Var.1.5 Dseg Syntax: Dseg Returns the base address of the Data segment. The value returned is an Integer. MS-DOS/PC-DOS and CP/M-86 179 . The index must be an address specified as the segment base address and an offset separated by a colon and both of type Integer.1.4. MemW. called Mem.

e. B. When a value is assigned to a component of Port or Port W it is output to the port specified.6 With Statements With statements may be nested to a maximum of 9 levels. Each element of the array represents a data port. Furthermore. As data ports are selected by 16-bit addresses the index type is Integer. its value is input from the port specified.1.2 Pointer Values In very special circumstances it can be of interest to assign a specific value to a pointer variable without using another pointer variable or it can be of interest to obtain the actual value of a pointer variable.7.1 . components of Port and PortW cannot be used as variable parameters to procedures and functions. The result is an Integer specifying the number of of available paragraphs on the heap.2 Port Array The Port and Port W array are used to access the data ports of the 8086/88 CPU.B. When a component of port is referenced in an expression.1. Example: Port[ 56] : = 10.1 The standard function MemAvail is available to determine the available space on the heap at any given time.1.1. operations referring to the entire port array (reference without index) are not allowed. with the index corresponding to port numbers. 180 TURBO Pascal Language Manual .2 Port Array 8. i. The use of the port array is restricted to assignment and reference in expressions only. The components of the Port array are of type Byte and the components of Port Ware of type Integer.1.5. (a paragraph is 16 bytes).7 Pointer Related Items MernA vail 8. B.5.7. 8.

Instead the functions and Seg must be used. B. immediately followed by the reserved word external and a filename specifying where to find the executable code for the subprogram.2. Only the subprogram heading is specified. $80).e. An external subprogram has no block.2 Obtaining The Value of a Pointer A pointer value is represented as a 32 bit entity and the standard function Ord can therefore not be used to obtain its value.1.1. Furthermore the external code must save the registers BP. Since it is impossible to know beforehand exactly where in the object code the external code will be placed this code must be relocatable.Assigning a Value to a Pointer 8.1 B. Example: POinter: =Pt r(Cseg. B. MS-DOS/PC-DOS and CP/M-86 181 . CS.1. ors The following statement obtains the value of the pointer P {which is a segment address and an offset}: SegmentPart : =Seg(p~ ). typically procedures and functions written in machine code. and no references must be made to the data segment. The function returns a 32 bit pointer consisting of a segment address and an offset. OffsetPart:=Ofs(P~).l. During compilation of a program containing external functions or procedures the associated files are loaded and placed in the object code.7. i.7.7.1 Assigning a Value to a Pointer The standard function Ptr can be used to assign specific values to a pointer variable. The reserved word external must be followed by a string constant specifying the name of a file in which executable machine code for the external procedure or function must reside. OS and SS and restore these before executing the RET instruction. no declaration part and no statement part.2.2.8 External Subprograms The reserved word external is used to declare external procedures and functions.

1.l. external 'QS'. Example: procedure Di skReset. The Execute procedure works exactly as if the program had been activated from the operating system (with the limitation that parameters can not be passed from the command line).1 ). and the syntax is exactly the same as that of calls to ordinary procedures and functions: procedure Plot(X.3. funct ion IOstatus: boo lean.e. If the file exists.8 External Subprograms The type of the filename is . external 'IOSTAT'. external 'PlDT'. external 'DSKRFSEI".1.B. previously assigned to a disk file with the standard procedure Assign.9 Chain and Execute TURBO Pascal provides two procedures Chain and Execute which allow you to activate other TURBO programs from a TU RBO program. 182 TURBO Pascal Language Manual .CMD in the CP/M-86 version. files compiled with the cH n-file option selected on the Options menu (see section B.Y: Integer). it uses the Pascal library already present in memory. 8. Only the code segment of a . The syntax of the procedure calls are: Chain(Fi Ie) Execute(File) where File is a file variable of any type.CHN files. Parameters may be passed to external subprograms.COM in the MS-DOS version and . i. The Chain procedure is used only to activate special TURBO Pascal .CMD file is loaded.1.12.1. Such a file contains only program code. no Pascal library. procedure QuickSort(var List: PartNo). it is loaded into memory and executed. External subprograms and parameter passing is discussed further in section B.

data. and stack segments to accommodate largest . end. Example: Program MAIN. . If the disk file does not exist.1. When the I compiler directive is passive ({$I-}). This is done by using the Options menu to change the minimum code. COM: program Ma i n.2 and B. Data can be transferred from the current program to the chained program either by shared global variables or by absolute address variables.8. The base addresses and sizes of the code. ~adln(Txt). the variables will be placed at the same address in memory by both programs.1. they may be shared.1.3 When these conditions are satisfied. begin Write('Enter any text: . both programs must be compiled to the same size of code and data segments (see sections B. This error is treated as described in section 14. var string[ 80] .1.). and as TURBO Pascal does not automatically initialize its variables. and they must be listed in the same order in both declarations. As s i gn( CntPrg.9 Chaining and eXecuting TURBO programs does not alter the memory allocation state. To insure overlapping. It is therefore imperative that the first program which executes a Chain statement allocates enough memory for the code. data and stack segments are not changed.Chain and Execute 8. program execution continues with the statement following the failed Chain or Execute statement. Chain(CntPrg) .CHN program. ChrCount . an I/O error occurs. ehn' ) . Txt: CntPrg: file. Furthermore. data and free memory sizes (see section B.1. shared global variables should be declared as the very first variables in both programs. and the IOresult function must be called prior to further I/O.1 ). MS-OOS/PC-OOS and CP/M-86 183 .1.

A variable identifier generates two bytes of code (in byte reversed format) containing the offset of the variable within its base segment. The constants may be either literal constants or constant identifiers.9 Chain and Execute Program CHRCQUNT. end. .1. Literals generate one byte of code if within the range 0 . .0. I: Integer. for I := 1 to length(Txt) do i f Txt[ I] in [ 'A' . variable identifiers.CHN: program ChrCount. var Txt: string[ 80] .. Writeln( '.1.. 255 ($OO . and they must be of type Integer. i. . or location counter references. Write( 'No of characters in entry: '.10 In -line Machine Code TURBO Pascal features the inline statements as a very convenient way of inserting machine code instructions directly into the program text. NoOfChar : = Length(Txt). NoOfUpc. Global. No of upper case characters: " NoOlUpc. 'Z'] then NoOfUpc . NoOfChar. otherwise two bytes in the standard byte reversed format.1 ).1. Constant identifiers always generate two bytes of code.'.e. 184 TURBO Pascal Language Manual . An inline statement consists of the reserved word inline followed by one or more constants.B. from a program run with the compiler options switch in position Memory (section B. $FF). separated by slashes and enclosed in parentheses.NoOfChar).. begin NoOfUpc . B. Note that neither Chain nor Execute can be used in direct mode.Succ(NoOfUpc).).1. local and typed constants occupies different segments as follows: Global variables resides in the data segment and the offset generated is relative to the OS register.

optionally followed by an offset consisting of a plus or a minus sign and an Integer constant. An asterisk alone generates two bytes of code (in byte reversed format) containing the current location counter value. {Str is type St ring[ 255] } { { { { L1 : { { { { { { { { { L2: LES MOO INC DED JZ INC CMP JB CMP JA SUB JMP } DI. SP.1. A location counter reference consists of an asterisk.Strg[BP] } CL. and SS must be restored to their original values before the inline statement. and inline statements may use all CPU registers. that the contents of the registers SP.28H} } SHORT Ll } Inline statements may be freely mixed with other statements throughout the statement part of a block.In -line Machine Code B.10 Local variables reside in the stack segment and the offset generated is relative to the S P register. however. If the asterisk is followed by an offset. Note. the registers SP. Strg: Str). When an inline statement terminates. DS. MS-DOS/PC-DOS and CP/M-86 185 . it is added or subtracted before coding the address. procedure UpperCase(var begin inline ($04/ $BE/St rg/ $26/ $8A/ $0D/ $FE/$C1/ $FE/$09/ $74/$13/ $47/ $26/$88/$3D/$61/ $72/$F5/ $26/$88/$3D/$7Aj $77/$EF/ $26/$88/$2D/$28/ $EB/$E9). The following example of an inline statement generates machine code that will convert all characters in its string argument to upper case. Typed constants reside in the code segment and the offset generated is relative to the CS register. ' z' } E8 : BYTE PI'R } L1 ES : BYTE PI'R [DIJ. DS. SP. and SS must be the same on exit as on entry.E8:[DIJ } CL } CL } L2 } DI E8 : BYTE PI'R [DI J . 'a'} } L1 [DI J . end.

SI. and they must themselves insure that all registers used are preserved. 186 TURBO Pascal Language Manual .1. Interrupt service routines must preserve all registers used. The programmer must initialize the interrupt vector used to activate the interrupt service routine.DX. which will override the RET instruction generated by the compiler.1. as these routines are not re-entrant.CX. CP/M -86 users should note that B DOS calls should not be performed from interrupt handlers. An interrupt service procedure should not employ any I/O operations using the standard procedures and functions of TURBO Pascal. This is done by placing the following inline statement in the very beginning of the procedure: in1 ina ($50/ $53/ $51/ $52/ $57/ $56/ $06/ $FB).1.11.11 Interrupt Handling B.11 Interrupt Handling The TURBO Pascal run time package and the code generated by the compiler are both fully interruptible.BP. B. Result will contain any values returned from the service routine. Such procedures must not have parameters. When the interrupt service routine returns control to your program.ES.1 Intr procedure Syntax: Intr( InterruptNo. It then makes the software interrupt given by the parameter interrupt No which must be an Integer constant. Result) This procedure initializes the registers and flags as specified in the parameter Result which must be of type: Resul t = record AX.BX. If required. as the BDOS is not re-entrant. and this inline statement at the very end of the procedure: in1 ine ($07 /$5E/$5F/$5A/$59/ $5B/ $58/ $OF).B.Flags: Integer.DI.DS. end. interrupt service procedures may be written in Pascal. The last instruction of the terminating inline statement is an IRET instruction ($CF).

1. B. and declared scalars with more than 256 possible values. These bytes contain a 2's complement 16-bit value with the least significant byte stored first. The segment base address can be determined by using the standard function Seg.1 Scalars The following scalars are all stored in a single byte: Integer subranges with both bounds in the range 0 .12 8. booleans. This byte contains the ordinal value of the variable. The following scalars are all stored in two bytes: Integers. Integer subranges with one or both bounds not within the range 0 . the symbol@ denotes the offset of the first byte occupied by a variable of the given type within its segment. but this structuring will not affect their internal formats. and typed constants occupy different segments as follows: Global variables reside in the data segment and the offset is relative to the OS register. Global and local variables.1 Basic Data Types The basic data types may be grouped into structures (arrays.1. 8. chars. and declared scalars with less than 256 possible values.1. Local variables reside in the stack segment and the offset is relative to the BP register. 255..1. All variables are contained within their base segment.12. and disk files). records.12.12 Internal Data Formats In the following descriptions.1. MS-OOS/PC-OOS and CP/M-86 187 .Internal Data Formats 8. Typed constants reside in the code segment and the offset is relative to the CS register. 255..

The sign of the mantissa is stored in this bit. giving a floating point value with a 40'-bit mantissa and an 8-bit 2's exponent.1.1. 8.1.B.1. Hence. however. i.2 Reals 8. In the table shown below. The exponent is stored in the first byte and the mantissa in the next five bytes which the least significant byte first: @ @ +1 Exponent LSB of mantissa MSB of mantissa @ +5 The exponent uses binary format with an offset of$80. the most significant bit (bit 7 of the fifth byte) should be interpreted as a 1. a 1 indicating that the number is negative.2 Reals Reals occupy 6 bytes. the floating point value is considered to be zero.12.12. If the exponent is zero. The following bytes contains the string with the first character stored at the lowest address.e. and Max denotes the maximum length: @ +1 @+2 @ @ @ Current length (L) First character Second character Last character Unused Unused +L +L+1 @+Max 188 TURBO Pascal Language Manual . The mantissa is always normalized.3 Strings A string occupies as many bytes as its maximum length plus one. The value of the mantissa is obtained by dividing the 40-bit unsigned integer by Z' 40. The first byte contains the current length of the string.1.1. and a 0 indicating that the number is positive. an exponent of $84 indicates that the value of the mantissa is to be multiplied by 2 ~ ($84$80) = 2 ~ 4 = 16. L denotes the current length of the string.12.

some of the bits are bound to be zero at all times and need therefore not be stored.12. The number of bytes occupied by a set variable is calculated as (Max div 8) (Min div 8) + 1. The value nil corresponds to two zero words.1.4 Sets An element in a Set occupies one bit. and TURBO therefore employs a compromise: Only bytes which are statically zero (i.2 Data Structures Data structures are built from the basic data types using various structuring methods.12. 8. Both are stored in memory using byte reversed format. bytes of which no bits are used) are not stored. The structuring of data does not in any way affect the internal formats of the basic data types.1. The memory address of a specific element E is: MemAddress = @ + (E div 8) . If a set contains less than 256 elements. The two least significant bytes contains the offset and the two most significant bytes the base address. Three different structuring methods exist: Arrays.12.Sets B. and disk files.1. the best way to store a set variable of a given type would then be to "cut off" all insignificant bits. In terms of memory efficiency. where Max and Min are the upper and lower bounds of the base type of that set.12. MS-DOS/PC-DOS and CP/M-86 189 . are quite slow.4 8.1. a set variable will never occupy more than 32 bytes (256/8).1. Such rotate operations.e.1. and as the maximum number of elements in a set is 256. records. i. 8. the least significant byte is stored first. and rotate the remaining bits so that the first element of the set would occupy the first bit of the first byte. however.5 Pointers A pointer consists of four bytes containing a segment base address and an offset.1. This method of compression is very fast and in most cases as memory efficient as the rotation method.(Min div 8) and the bit address within the byte at MemAddress is: BitAddress = E mod 8 where E denotes the ordinal value of the element.e.

4 and B.81 Boardf2.21 Boardf1. the total number of bytes occupied by the record is given by the length of the fixed part plus the length of largest of its variant parts. 190 TURBO Pascal Language Manual .1.2.1.2.2 Records The first field of a record is stored at the lowest memory address. 8.81 8.12.2.11 Boardf1..3.1 Arrays The components with the lowest index values are stored eft the lowest memory address..11 Boardf2.2.1.1 .g.12. e.21 Highest address:Boardf8.12.2.4 .B. If the record contains no variant parts. A disk file is controlled through a file interface block (FIB) as described in sections B.1 Arrays 8. Each variant starts at the same memory address.3 Disk Files Disk files are different from other data structures in that data is not stored in internal memory but in a file on an external device. 8. A multi-dimensional array is stored with the rightmost dimension increasing first. If a record contains a variant. given the array Board: arr~[l . the length is given by the sum of the lengths of the individual fields.1. 8] of Square you have the following memory layout of its components: lowest address: Boardf1.12. In general there are two different types of disk files: random access files and text files.

at higher addresses on the stack. WORKARFA MS-OOS/PC-OOS and CP/M-86 191 . 8.12.12. The parameters.2. then the stack upon entry to Magic would have the following contents: < < < < Function result Segment base address of R Offset address of R Mantissa of R next 5 bytes > > > > > > > > < First character of S < Last character of S < Length of S < Return address SP An external subroutine should save the Base Page register (BP) and then copy the Stack Pointer SP into the Base Page register in order to be able to refer to parameters. are located below the return address.1.12.Text Files 8. i. S: string5): Integer. On entry to an external subroutine. This can be obtained by the following instructions: PUSH BP MOV BP.1. Each line consists of any number of characters ended by a CR/LF sequence (ASCII $00/ $OA). Furthermore the subroutine should reserve space on the stack for local workarea. The file is terminated by a Ctrl-Z (ASCII $1B). If an external function has the following subprogram header: function Magic(var R: Real.3 Parameters Parameters are transferred to procedures and functions via the stack which is addressed through SS:SP. if any. the top of the stack always contains the return address within the code segment (a word).4 B.2. but a text file is furthermore divided into lines.e.SP SUB SP.1.4 Text Files The basic components of a text file are characters.

The following instructions should therefore be used when exiting from a subprogram: MOV FQP ~ SP.2 Value Parameters With value parameters. 192 TURBO Pascal Language Manual .12. 8. two words are transferred on the stack giving the base address and offset of the first byte occupied by the actual parameter.BP BP NoOfBytesTtiRemove 8.1.12. [BP-l] Before executing a RET instruction the subprogram must reset the Stack Pointer and Base Page register to their original values. SP The following instruction will load length of the string into the AL register: MOV AL.B.3.3 Parameters The last instruction will have the effect of adding the following to the stack: < Return address > BP < TbB saved BP register > < First byte of local ~orkarea > < Last byte of local work area> Parameters are accessed via the BP register.1.3. When executing the RET the parameters may be removed by giving RET a parameter specifying how many bytes to remove.1.1 Variable Parameters With a variable (var) parameter.12. the data transferred on the stack depends upon the type of the parameter as described in the following sections.

12.5 Pointers A pointer value is transferred on the stack as two words containing the base address and offset of a dynamic variable.3.3.4 Sets A set always occupies 32 bytes on the stack (set compression only applies to the loading and storing of sets).12.12.2 Reals A real is transferred on the stack using six bytes.1.2. Array and Record parameters are not actually transferred on the stack. The value NIL corresponds to two zero words.3.1. If the variable occupies only one byte when it is stored. B .1.12. B.3 Strings When a string is at the top of the stack. MS-DOS/PC-DOS and CP/M-86 193 .1 Scalars Integers.Scalars 8. B. It is then the responsibility of the subroutine to use this information to make a local copy of the variable.1 . B.1 B.2.2.1. Instead.2.3. Chars and declared scalars (Le. B.3.12. the most significant byte of the parameter is zero.2.12.3.6 Arrays and.1. all scalars except Reals) are transferred on the stack as a word.2. two words containing the base address and offset of the first byte of the parameter are transferred.12. the topmost byte contains the length of the string followed by the characters of the string.1.3.2. Booleans.Records Even when used as value parameters.

3. and a Stack Segment Two stack-like structures are maintained during execution of a program: the heap and the stack. = = Reals must be returned on the stack with the exponent at the lowest address. the heap pointer HeapPtr is set to low memory in the stack segment and the heap grows upwards towards the stack.12.4 Function Results 8.5 The Heap and The Stacks During execution of TURBO Pascal program the following segments are allocated for the progam: a Code Segment. Boolean functions must return the function value by setting the Z flag (Z False.1.1 2. except Reals. must be returned in the AX register.1. NZ True). User written external functions must return their results exactly as specified in the following: Values of scalar types.4 Function Results User written external functions must remove all parameters and the function result from the stack when they return. a Data Segment. and is controlled with the standard procedures New.1 . 8. The heap is used to store dynamic variables.3. Pointer values must be returned in the DX:AX. Sets must be returned on the top of the stack according to the format described in section B. If the result is only one byte then AH should be set to zero. On exit SP must point at the byte containing the string length.2.12.B. 194 TURBO Pascal Language Manual . At the beginning of a program. and Release.1. The pre-defined variable HeapPtr contains the value of the heap pointer and allows the programmer to control the position of the heap. Mark. This is done by not removing the function result variable when returning.12.

MS-DOS/PC-DOS and CP/M-86 195 . If a collision has occurred.The Heap and The Stacks 8. the stack pointer is set to the address of the top of the stack segment. On each call to the procedure New and on entering a procedure or function. At the beginning of a program.1. intermediate results during evaluation of expressions and to transfer parameters to procedures and functions. an execution error results.5 The stack is used to store local variables.12. the system checks for collision between the heap and the recursion stack. unless the K compiler directive is passive ({$K-}).

B.2

The MS-DOS / PC-DOS Implementations

8.2

The MS-DOS / PC-DOS Implementations

This section covers items peculiar to the MS-DOS and PC-DOS versions of TURBO Pascal. For the sake of clarity and ease, these two operating systems will simply be referred to as DOS in the following.

8.2.1

Standard Identifiers

The following standard identifiers are unique to the DOS implementations:

LongFilePos LongFileSize

LongSeek MsDos

8.2.2

Function Calls

For the purpose of making DOS system calls, TURBO Pascal introduces a procedure MsDos, which has a record as parameter. Details on DOS system calls and BIOS routines are found in the MS-DOS Operating System Manual published by MicroSoft. The parameter to MsDos must be of the type: record

AX,BX,CX,DX,BP,SI,DI,DS,ES,Flags: Integer;
end;

Before TURBO makes the DOS system call the registers AX, BX, CX, OX, BP, SI, 01, OS, and ES are loaded with the values specified in the record parameter. When DOS has finished operation the MSdos procedure will restore the registers to the record thus making any results from DOS available.

8.2.3

User Written I/O Drivers

For some applications it is practical for a programmer to define his own input and output drivers, i.e. routines which perform input and output of characters to and from an external device. The following drivers are part of the TURBO environment, and used by the standard I/O drivers (although they are not available as standard procedures or functions):

196

TURBO Pascal Language Manual

User Written I/O Drivers

8.2.3

function function procedure procedure procedure function procedure function

CanSt: boolean; { 11 } Canln: Char; { 8 } CanOut(Ch: Char); {2 } LstOut(Ch: Char); { 5 } AuxOut(Ch: Char); {4} Auxin: Char; { 3 } UsrOut(Ch: Char); {2 } Usrln: Char; { 8 }

The CanSt routine is called by the function KeyPressed, the Canln and CanOut routines are used by the CON:, TRM:, and KB D: devices, the LstOut routine is used by the LST: device, the AuxOut and Auxin routines are used by the AUX: device, and the UsrOut and Usrln routines are used by the USR: device. By default, these drivers are assigned to the DOS system calls as showed in curly brackets in the above listing of drivers. This, however, may be changed by the programmer by assigning the address of a self-defined driver procedure or a driver function to one of the following standard variables:
Variable Contains the address of the

CanStPtr CanlnPtr CanOutPtr LstOutPtr AuxOutPtr AuxlnPtr UsrOutPtr UsrlnPtr

CanSt function Canln function Can Out procedure LstOut procedure AuxOut procedure Auxin function UsrOut procedure Usrln function

A user defined driver procedure or driver function must match the definitions given above, i.e. a CanSt driver must be a boolean function, a Canln driver must be a char function, etc.

MS-DOS/PC-DOS and CP/M-86

197

B.2.4

File Interface Blocks

B.2.4

file Interface Blocks

Each file variable in a program has an associated file interface block (FIB). A FIB occupies 176 bytes of memory and is for files of type text divided into two sections: The control section (the first 48 bytes), and the sector buffer (the last 128 bytes). The control section contains various information on the disk file or device currently assigned to the file. The sector buffer is used to buffer input and output from and to the disk file. Random access file variables and untyped file variables does not have buffer section and therefore occupies only 48 bytes. The table below shows the format of a FIB: @ @+1 @+2 @+3 @+4 @+7 @+8 @ +10 @+11 @+25 @+26 @+44 @+47 @ +48 @ +175 Flags byte File type iCharacter buffer Sector buffer pointer Number of records (LSB) Number of records (MSB) Unused (reserved) Unused (reserved) First byte of DOS FCB Record length in bytes (LSB) Record length in bytes (MSB) Current record number (LSB) Current record number (MSB). (Last byte of FCB) First byte of sector buffer Last byte of sector buffer

The flags byte at@ contains two one-bit flags which indicate the current status of the file: bit 0 bit 1 Input flag. High if input is allowed. Output flag. High if output is allowed.

The file type field at@ + 1 specifies the type of device currently assigned to the file variable. The following values can occur:

198

TURBO Pascal Language Manual

File Interface Blocks

B.2.4

o
1

2

3
4 5 6

The console device (CON:) The terminal device (TRM:) The keyboard device (KB D:) The list device (LST:) The auxiliary device (AUX:) The user device (USR:) A disk file

When a file is assigned to a logical device, only the first three bytes of the FIB are of significance. The sector buffer pointer at @ +3 contains an offset from the first byte of the sector buffer. The 'number of records' field starting at@ +4 is a 32-bit number. All DOS file I/O is performed through system functions 39 and 40 {random block read and random block write), and the record length field in the FCB is always set to 1. The sector buffer starting at @ +48 is included in file variables of type Text only. Random access file variables and untyped file variables occupy only 48 bytes, and data is always transferred directly to or from the variable to be read or written, leaving all blocking and deblocking to DOS.

8.2.5

Random Access Rles

A random access file consists of a sequence of records, all of the same length and same internal format. To optimize file storage capacity, the records of a file are totally contiguous. TU RBO saves no information about the record length. The programmer must therefore see to it that a random access file is accessed with the correct record length. The size returned by the standard function Filesize is obtained form the DOS directory.

MS-DOS/PC-DOS and CP/M-86

199

B.2.6

Operations on Files

B.2.6

Operations on Files

B.2.6.1

Extended File Size

The following three additional file routines exist to accommodate the extended range of records in DOS. These are: LongFileSize function, LongFilePosition function, and LongSeek procedure They correspond to their Integer equivalents FileSize, File Position, and Position but operate with Rea Is . The functions thus return results of type Real, and the second parameter of the LongSeek procedure must be an expression of type Real.

B.2.6.2

File of Byte

In the CP/M implementations, access to non-TURBO files (except text files) must be done through untyped files because the two first bytes of typed TURBO files always contain the number of components in the file. This is not the case in the DOS versions, however, and a non-TURBO file may therefore be declared as a file of byte and accessed randomly with Seek, Read, and Write.

B.2.6.3

Flush Procedure

The Flush procedure has no effect in DOS, as DOS file variables do not employ a sector buffer.

200

TURBO Pascal Language Manual

8.1 Standard Identifiers The standard identifier Bdos is unique to the CP/M-86 implementation 8. which has a record as parameter. BP. { 6 } ConOut(Ch: Char). DI.3. When the BDOS has finished operation the Bdos procedure will restore the registers to the record thus making any results from the B DOS available. TURBO Pascal introduces a procedure Bdos. The parameter to Bdos must be of the type: record AX.2 Function Calls For the purpose of calling the CP/M-86 BDOS.3 B.ES. { 6 } MS-DOS/PC-DOS and CP/M-86 201 .3.BX. DX. end.DS. and ES are loaded with the values specified in the record parameter. Details on BDOS and BIOS routines are found in the CP/M-86 Operating System Manual published by Digital Research. { 6 } LstOut(Ch: Char). DS. routines which perform input and output of characters to and from an external device. {6} Conln: Char. { 6 } Usrln: Char. The following drivers are part of the TURBO environment.DI.DX. i. BX. { 3 } UsrOut(Ch: Char).BP. CX. { 5 } AuxOut(Ch: Char).SI.3. and used by the standard I/O drivers (although they are not available as standard procedures or functions): function function procedure procedure procedure function procedure function ConSt: boolean.The CP/M-86 Implementation B. SI.e.3 User Written I/O Drivers For some applications it is practical for a programmer to define his own input and output drivers.CX. Before TURBO calls the BDOS the registers AX.Flags: Integer. {4} AuxIn: Char.3 The CP/M -86 Implementation 8.

a ConSt driver must be a boolean function. a Conln driver must be a char function.B.e. etc. the AuxOut and AuxIn routines are used by the AUX: device. the LstOut routine is used by the LST: device. By default. i.4 Rle Interface Blocks Each file variable in a program has an associated file interface block (FIB). however. 202 TURBO Pascal Language Manual . The sector buffer is used to buffer input and output from and to the disk file. B. A FIB occupies 176 bytes of memory and is divided into two sections: The control section (the first 48 bytes). the Conln and ConOut routines are used by the CON:.3 User Written I/O Drivers The ConSt routine is called by the function KeyPressed. may be changed by the programmer by assigning the address of a self-defined driver procedure or a driver function to one of the following standard variables: Variable ConStPtr ConlnPtr ConOutPtr LstOutPtr AuxOutPtr AuxlnPtr UsrOutPtr UsrlnPtr Contains the address of the ConSt function Conln function Con Out procedure LstOut procedure AuxOut procedure AuxIn function UsrOut procedure Usrln function A user defined driver procedure or driver function must match the definitions given above.3. This.3. these drivers are assigned to the BOOS functions as showed in curly brackets in the above listing of drivers. The control section contains various information on the disk file or device currently assigned to the file. and KBD: devices. and the UsrOut and Usrln routines are used by the USR: device. and the sector buffer (the last 128 bytes). TRM:.

The file type field at@ + 1 specifies the type of device currently assigned to the file variable.4 The table below shows the format of a FI B: @ @ +1 @+2 @+3 @+4 @+5 @+6 @+7 @+8 @+9 +10 +11 @ +12 @ @ Flags byte File type Character buffer Sector buffer pointer Number of records (LSB) Number of records (MSB) Record length in bytes (LSB) Record length in bytes (MSB) Current record number (LSB) Current record number (MSB) Unused (reserved) Unused (reserved) First byte of CP/M FCB Last byte of CP/M FCB First byte of sector buffer Last byte of sector buffer @+47 @+48 @ +175 The flags byte at@ contains four one bit flags which indicate the current status of the file: bit 0 bit 1 bit 2 bit 3 Input flag. Read semaphore. Output flag. High if output is allowed.3. The following values can occur: o 1 2 3 4 5 6 The console device (CON:) The terminal device (TRM:) The keyboard device (KBD:) The list device (LST:) The auxiliary device (AUX:) The user device (USR:) A disk file MS-DOS/PC-DOS and CP/M-86 203 . Write semaphore. High if input is allowed. High if data has been written to the sector buffer. High if the contents of the sector buffer is undefined.File Interface Blocks B.

all of the same length and same internal format. the records of a file are totally contiguous. sector 0. byte byte byte byte 0: 1: 2: 3: Number of records (LSB) Number of records (MSB) Record length (LSB) Record length (MSB) 204 TURBO Pascal Language Manual . Bytes@ + 10 and @ + 11 are currently unused.3. The first record of the file is stored starting at the fourth byte. sector 0. The last block of the FIB is the sector buffer used for buffering input and output from and to disk files. Bytes@ +12 through@ +47 contain a CP/M file control block (FCB). Each field consists of two bytes in byte reversed format.4 File Interface Blocks The sector buffer pointer at @ +3 contains an offset from the first byte of the sector buffer. only the first three bytes of the FIB are of significance. To optimize file storage capacity. as data is transferred directly between a variable and the disk file.B. The FIB of an untyped file has no sector buffer. The following three fields are used only by random access files (defined files) and untyped files. When a file is assigned to a logical device. The FIB format described above applies to all defined files and textfiles. but reserved for future expansion. the length of the FIB of an untyped file is only 48 bytes. Thus.3. sector 0. The first four bytes of the first sector of a file contains the number of records in the file and the length of each record in bytes. sector 0.5 Random Access Rles A random access file consists of a sequence of records. 8.

Write (var F: text. Read (var F: text. Readln (var F: text). var R: Real). var C: Char). S:string). SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS This appendix lists all standard procedures and functions available in TURBO Pascal and describes their syntax. Read (var F: text. B: Boolean). Write (var F: text. The following symbols are used to denote elements of various types: type string file scalar pointer any type any string type any file type any scalar type any pointer type Where parameter type specification is not present. var S:string). it means that the procedure or function accepts variable parameters of any type. Read (var F: text. var v: type). Write (var F: text. Write (var F: file of type. R: Real). and their types. C: Char). Write (var F: text. SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS 205 . Read (var F: text. Write (var F: text. var v: type). C.SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS C C. var I: Integer). I: Integer).1 Input/Output Procedures and Functions The following procedures use a non-standard syntax in their parameter lists: procedure Read (var F: file of type. Writeln (var F: text). thewir parameters.

206 TURBO Pascal Language Manual . C. Ord (X: scalar): Integer. Int (R: Real): Real. Sqr (R: Real): Real. Ln (R: Real): Real. Pred (X: scalar): scalar. Cos (R: Real): Real. Succ (X: scalar): scalar.4 Transfer Functions function Chr (I: Integer): Char. C. Exp (R: Real): Real.2 Arithmetic Functions function Abs (/: Integer): Integer. Abs (R: Real): Real. Round (R: Real): Integer. Sqrt (R: Real): Real. Sin (R: Real): Real.3 Scalar Functions function Odd (/: Integer): Boolean. ArcTan (R: Real): Real. Trunc (R: Real): Integer.C. Frac (R: Real): Real. Sqr (/: Integer): Integer.2 Arithmetic Functions C.

. Source: string): Integer. Len: Integer): string. var Dest: Type. Rename (var F: file. P: Integer). Pos: Integer). var/.Sn: string): string.String Procedures and Functions C. Pos: Integer). Num: Integer). Name: string). FilePos (var F: file of type): Integer. Rewrite (var F:file). FileSize (var F: file): Integer.S2. Eoln (var F: Text): Boolean. Insert (S:string. var Dest: Type.s String Procedures and Functions The Str procedure uses a non-standard syntax for its numeric parameter. Seek (var F: file. FilePos (var F: file): Integer. Str (R: Real. var p: Integer). function Concat (S1 . Copy (S: string. Seek (var F: file of type. Close (var F:file). Len: Integer).. BlockWrite (var F: file.6 File handling routines procedure Assign (var F: file.5 C. BlockRead (var F: file. Pos. Val (S:string. Execute (var F: file). procedure Delete (var S:string. Reset (var F:file). paS: Integer). . Pos. Num: Integer). Chain (var F: file). C. var S:string). function Eof (var F:file): Boolean. var D: string. var S:string). Str (/: Integer. Length (S:string): Integer.. Val (S:string. var R: Real. name: string). Pas (Pattern. SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS 207 . FileSize (var F: file of type): Integer. Erase (var F: file).

param: Integer). 208 TURBO Pascal Language Manual . C. length: Integer. GotoXY (X. FillChar (var dest. function MemAvail : Integer.param: Integer). Delay (mS: Integer).C. Ord (P:pointer): Integer. DelLine.dest. C. NormVideo. data: Char). Crtlnit. length: Integer). Move (var source. Y: Integer). Halt. FiIIChar (var dest.s Screen Related Procedures procedure CrtExit. length: Integer. New (var P:pointer). Release (var P:pointer). InsLine. I: Integer).9 Miscellaneous Procedures and Functions procedure Bdos (func. data: byte). Randomize. ClrEol. LowVideo. Ptr (/: Integer):pointer. Bios (func. ClrScr.7 Heap Control Procedures and Functions procedure GetMem (var P: pointer.7 Heap Control Procedures and Functions C. Mark (var P:pointer).

Bios (Func. KeyPressed : Boolean. Param: Integer): Integer. IOresult : Boolean. B dosH L (Func. Addr (procedure identifier»): Integer. La (/: Integer): Integer. Random (Range: Integer): Integer. Param: Integer): Integer. B iosH L (Func.9 function Addr (var variable): Integer. SizeOf (type identifier»): Integer. UpCase (Ch: Char): Char. Param: Integer): byte.Miscellaneous Procedures and Functions C. Param: Integer): Byte. SizeOf (var variable): Integer. Hi (/: Integer): Integer. Bdos (Func. Swap (/: Integer): Integer. Addr (function identifier»): Integer. Random: Real. SUMMARY OF STANDARD PROCEDURES AND FUNCTIONS 209 .

9 Miscellaneous Procedures and Functions Notes: 210 TURBO Pascal Language Manual .G.

Real as operand Integer Boolean Integer Boolean * / div mod. Real string as operand Integer.unary not Operation sign ident i ty sign inversion negation mul t ipl icat ion set intersection division Integer division modulus arithmeticl and logical and shift left shift right addition concatenation set union subtraction set difference arithmeticl or logical or ari thmet ic 1 xor logical xor TYPe of operand(s) Integer. string any set Integer. Integer Integer Real Real Operator + unary . Boolean Integer. any set Integer Boolean Integer Boolean Real type Real type TYPe of resul t as operand as operand as operand Integer. Real.he operators are grouped in order of decending precedence. Real Integer. the result is as follows: Operands Result Integer. Real Real.SUMMARY OF OPERATORS D D. Real Integer Integer Integer Boolean Integer Integer Integer. T. Real any set type Integer. Integer Real. SUMMARY OF OPIERATORS The following table summrizes all operators of TURBO Pascal. Real Integer. Where Type of operand is indicated as Integer. and shl shr + or xor SUMMARY OF OPERATORS 211 . Real as operand Real Integer Integer Integer Boolean Integer Integer Integer.

D SUMMARY OF OPERATORS <> > < in equal i ty equal i ty equal i ty equal i ty inequal i ty inequal i ty inequal i ty inequal i ty greater or equal greater or equal set inc lus ion less or equal less or equal set inc lus ion greater than greater than less than less than set membership any scalar type string any set type any pOinter type any scalar type string any set type any pOinter type any scalar type st ring any set type any scalar type string any set type any scalar type string any scalar type st ring see below Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boo lean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean Boolean The first operand of the in operator may be of any scalar type. and the second operand must be a set of that type. 212 TURBO Pascal Language Manual .

IMPORTANT NOTICE All compiler directives have default values. A compiler directive is introduced as a comment with a special syntax which means that whenever a comment is allowed in a program. a compiler directive is also allowed. SUMMARY OF COMPILER DIRECTIVES A number of features of the TURBO Pascal compiler are controlled through compiler directives.SUMMARY OF COMPILER DIRECTIVES E E.R+.} {$I INCLUDE. and a minus sign indicates that is disabled (passive). FIL} {$B-. ultimately terminated by a closing bracket. These have been chosen to optimize execution speed and minimize code size. Examples: {$I . A compiler directive consists of an opening bracket immediately followed by a dollar-sign immediately followed by one compiler directive letter or a list of compiler directive letters separated by commas.g. A + sign after a directive indicates that the associated compiler feature is enabled (active). This means that e. Check below to make sure that your programs include the required compiler directive settings! SUMMARY OF COMPILER DIRECTIVES 213 . code generation for recursive procedures (CP/M-80 only) and index checking has been disabled.V-} ( *$X-*) Notice that no spaces are allowed before or after the dollar-sign.

{$C-J.I/O Error Handling Default: 1+ The I directive controls I/O error handling. 214 TURBO Pascal Language Manual . See section 14. When passive. all I/O operations are checked for errors.E. {$C+J.1.Control Sand C Default: c+ The C directive controls control character interpretation during console I/O. E. When passive. you should switch off this directive. a Ctrl-C entered in response to a Read or Readln statement will interrupt program execution.5.2 C .1 Common Compiler Directives E. This directive is global to an entire program block and cannot be re-defined throughout the program. When active. When active. the default input/output channel.6.3 and 14.4 I .1.1. Include files are discussed in detail in chapter 1 7 .8 for further details.Include Rles The I directive succeeded by a file name instructs the compiler to include the file with the specified name in the compilation. i. and a Ctrl-S will toggle screen output off and on. the TRm: device is used. The active state slows screen output somewhat. { $B+}. {$I+J. This directive is global to an entire program block and cannot be redefined throughout the program.1 for further details. When active. {$I-J. { $B-I. E. E. so if screen output speed is imperative.1 B-1 /0 Mode Selection Default: B+ The B directive controls input/output mode selection.1 Common Compiler Directives E.1. it is the responsibility of the programmer to check I/O errors through the standard function IOresult. See sections 14.3 I .e. When passive. the CON: device is assigned to the standard files Input and Output. control characters are not interpreted.

{$U+}.l. See sections A.3 for further details.1.User Interrupt u- The U directive controls user interrupts.1 . the user may interrupt the program anytime during execution by entering a Ctrl-C. E. { $V+}.e. no checks are performed.5 R . all array indexing operations are checked to be within the defined bounds.4 and 10.Index Range Check E. When active. For forther discussion. {$V -}. When passive. It is a good idea to activate this directive while developing a program. When active.5 E. strict type checking is performed. the compiler allows passing of actual parameters which do not match the length of the formal parameter.R .l.7 Default: U . this has no effect. and index errors may well cause a program to go haywire.1. {$U-}. i. When passive.3 and B. and all assignments to scalar and subrage variables are checked to be within range. Activating this directive will significantly slow down execution speed. When active. execution will be speeded up by setting it passive (the default state).l. the lengths of actual and formal parameters must match. SUMMARY OF COMPILER DIRECTIVES 215 . {$R-J. Once debugged. see sections 8. {$R+}.6 V . E. When passive.Index Range Check Default: RThe R directive controls run-time index checks.Var-parameter Type Checking Default:V+ The V compiler directive controls type checking on strings passed as varparameters.

E. E. see sections 8 and 16. When passive. When active. i. This code requires more memory and executes slower.Array Optimization Default: X+ The X directive controls array optimization. [$X-]. For further information. please refer to section 11.e. For further details. the number of records which may be 'opened' within one block.1 A . E.E.2 W . [$A-]. code.e. When passive. 216 TURBO Pascal Language Manual . [$X+].3 X . This is discussed further in section 10.Nesting of With Statements Default: W2 The W directive controls the level of nesting of With statements.Absolute Code Default: A+ The A directive controls generation of absolute.2. [$A+]. The W must be immediately followed by a digit between 1 and 9.2.2 CP/M-BO Compiler Directives The following directives are unique to the CP/M-80 implementation. the compiler minimizes the code size instead. i. When active.1. non-recursive. absolute code is generated.2. the compiler generates code which allows recursive calls.2. code generation for arrays is optimized for maximum speed.

When passive. {$K-}.K . SUMMARY OF COMPILER DIRECTIVES 217 .3. t$K +}. a check is made to insure that space is available for local variables on the stack before eack call to a subprogram.Stack Checking Default: K+ The K directive controls the generation of stack check code.3.3 CP/M-a6/ MS-DOS / PC-DOS Compiler Directives The following directive is unique to the CP/M-86 / MS-DOS implementations: £. When active. no checks are made.1 E.1 K .Stack Checking E.

Stack Checking Notes: 218 TURBO Pascal Language Manual .3.1 K .E.

The reason for this is threefold: Firstly Read and Write gives much faster I/O.3 Get and Put The standard procedures Get and Put are not implemented. and secondly it offers compatibility with other popular Pascal compilers (e. The procedure New will not accept variant record specifications.g.2 Recursion CP/M -80 version only: Because of the way local variables are handled during recursion. and thirdly the Read and Write procedures are far more versatile and easier to understand that Get and Put. is easily circumvented by using the standard procedure GetMem. with only minor differencies introduced for the sheer purpose of efficieny. These differencies are described in the following. and Release instead of the New and Dispose procedures suggested by Standard Pascal. UCSD Pascal). Notice that the extensions offered by TURBO Pascal are not discussed. F. Primarily this deviation from the standard is far more efficient in terms of execution speed and required support code.TURBO Vs. This restriction. STANDARD PASCAL F F. a variable local to a subprogram must not be passed as a varparameter in recursive calls. STANDARD PASCAL The TURBO Pascal language closely follows the Standard Pascal defined by Jensen & Wirth in their User Manual and Report. Instead. TURBO Vs. F. F. as file buffer variables are not required. TURBO VS. the Read and Write procedures have been extended to handle all I/O needs.1 Dynamic Variables Dynamic variables and pointers use the standard procedures New. however. secondly variable space overhead is reduced. Mark. STANDARD PASCAL 219 .

as the CP/M operating system does not define a form-feed character.4 Goto Statements A goto statement must not leave the current block. F. F. F. This is because packing occurs automatically whenever possible. standard procedures Pack and Unpack are not implemented.S Page Procedure The standard procedure Page is not implemented.FA Goto Statements F.S Packed Variables The reserved word packed has no effect in TURBO Pascal. but it is still allowed. 220 TURBO Pascal Language Manual .7 Procedural Parameters Procedures and functions cannot be passed as parameters. For the same reason.

Simple expression expected String constant expected COMPILER ERROR MESSA GES 221 .COMPILER ERROR MESSA GES G G.' expected '.: expected BEGIN expected DO expected END expected 0 F expected TH EN expected TO or DOWNTO expected Boolean expression expected File variable expected I nteger constant expected I nteger expression expected Integer variable expected Integer or real constant expected I nteger o~ real expression expected I nteger or real variable expected Pointer variable expected Record variable expected Simple type expected Simple types are all scalar types. When encountering an error. Explanatory texts will only be issued if you have included error messages (answer V to the first question when you start TURBO). except real. the compiler will always print the error number on the screen. Many error messages are totally self-explanatory. 01 02 03 04 05 06 07 08 09 10 11 12 13 . 14 15 17 18 20 21 22 23 24 25 26 27 28 29 30 31 32 '.' expected ':' expected ' " expected '(' expected ')' expected ' =' expected ': =' expected '[' expected ']' expected ' . but some need a little elaboration as provided in the following. COMPILER ERROR MESSAGIES The following is a listing of error messages you may get from the compiler.

4) Types of operands in an expression are not compatible. constant. 255. type. or field identifier. Type mismatch 1) Incompatible types of the variable and the expression in an assignment statement 2) Incompatible types of the actual and the formal parameter in a call to a subprogram. Reserved word These may not be used as identifiers.g. or syntaxt error in statement. 222 TURBO Pascal Language Manual . Invalid string length The length of a string must be in the range 1.G COMPILER ERROR MESSAGES 33 34 35 36 37 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 String expression expected String variable expected Textfile expected Type identifier expected Untyped file expected Undefined label A statement references an undefined label. Lower bound )" upper bound The ordinal value of the upper bound must be greater than or equal to the ordinal value of the lower bound. except real. Duplicate identifier or label This identifier or label has already been used within the current block. Undefined pointer type in preceding type definitions A preceding pointer type definition contains a reference to an unknown type identifier. String constant length does not match type Invalid subrange base type Valid base types are all scalar types. Illegal assignment String constant exceeds line String constants must not span lines. and pointer types.. 'A' div '2' I nvalid result type Valid types are all scalar types. variable. string types. Constant out of range Constant and CASE selector type does not match Operand type(s) does not match operator E. Unknown identifier or syntax error Unknown label. 3) Expression type incompatible with index type in array assignment.

e. Invalid GOTO A GOTO cannot reference a label within a FOR loop from outside that FOR loop..tax of Real constants is defined in section 4. Label not within current block A GOTO statement cannot reference a label outside the current block.2.0. The program probably has more begins than ends. Illegal character in identifier Constants are not allowed here Files and pointers are not allowed here Structured variables are not allowed here Textfiles are not allowed here Textfiles and untyped files are not allowed here Untyped files are not allowed here I/O not allowed here Variables of this type cannot be input or output. but the body never occurred.2. 2) The absolute clause may not be used in a record.COMPILER ERROR MESSA GES G 56 57 58 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 90 91 Error in integer constant An Integer constant does not conform to the syntax described in section 4. COMPILER ERROR MESSA GES 223 .. Files must be VAR parameters File components may not be files file of file constructs are not allowed. 32767. Unexpected end of source Your program cannot end the way it does. Whole Real numbers should be followed by a decimal point and a zero. 255. I nvalid ordering of fields Set base type out of range The base type of a set must be a scalar with no more than 256 possible values or a subrange with bounds in the range 0 . Undefined FORWARD procedure(s) A subprogram has been forward declared. File not found The specified include file does not exist. INLINE error Illegal use of ABSOLUTE 1) Only one identifier may appear before the colon in an absolute variable declaration. Error in real constant The syn. 123456789.g. or it is not within the Integer range -32768 .

(CP/M-SO'only). Break your source text into smaller segments and use include files. M emory overflow You are trying to allocate more storage for variables than is available. Compiler overflow There is not enough memory to compile the program. however. used by the stack and the symbol table during compilation. Default is 2. This error may occur even if free memory seems to exist. 224 TURBO Pascal Language Manual . it is.G COMPILER ERROR MESSAGES 97 98 99 Too many nested WITHs Use the W compiler directive to increase the maximum number of nested WITH statements.

Out of integer range. Ln argument error. and addr is the address in the program code where the error occurred. Scalar or subrange out of range. Index expression is not within 1 . Heap/stack collision. The value assigned to a scalar or a subrange variable was out of range. and there is insufficient free memory. Division by zero attempted. I nvalid string index. The index expression of an array subscript was out of range. The following contains explanations of all run-time error numbers. Notice that the numbers are hexadecimal! 01 02 03 04 10 Floating point overflow. Sqrt argument error. A call was made to the standard procedure New or to a recursive subprogram.. Delete or Insert procedure calls. String length error. PC=addr Program aborted where NN is the run-time error number. The argument passed to the Sqrt function was negative. 1) A string concatenation resulted in a string of more than 255 characters. RUN-TIME ERROR MESSAGES Fatal errors at run-time result in a program halt and the display of the message: Run-time error NN. The real value passed to Trunc or Round was not within the Integer range -32767. I ndex out of range.RUN-TIME ERROR MESSAGES H H..32767. 11 90 91 92 FF RUN-TIME ERROR MESSAGES 225 . The argument passed to the Ln function was zero or negative. 255 with Copy. 2) Only strings of length 1 can be converted to a character.

H RUN-TIME ERROR MESSAGES Notes: 226 TURBO Pascal Language Manual .

Erase. which is an input-only device. If I/O error checking is passive (1$1-}). 02 03 I/O ERROR MESSAGES 227 . 1) You are trying to read (with Read or Readln) from a file without a previous Reset or Rewrite. possibly hanging the program. % ERROR MESSAGES An error in an input or output operation at run-time results in in I/O error. File not open for input. an I/O error causes the program to halt and the following error message is displayed: I/O error NN. 1) You are trying to write (with Write or Writeln) to a file without a previous Reset or Rewrite. If I/O checking is active (I compiler directive active). Notice that the numbers are hexadecimal! 01 File does not exist. or Chain does not specify an existing file. The file name used with Reset. PC=addr Program aborted where NN is the I/O error number. and addr is the address in the program code where the error occurred. Rename. 3) You are trying to read from the logical device LST:. I nstead. 2) You are trying to read from a text file which was prepared with Rewrite (and thus is empty). File not open for output. an I/O error will not cause the program to halt. If I/O is attempted before 10result is called after en error. a new error occurs. 2) You are trying to write to a text file which was prepared with Reset. all further I/O is suspended until the result of the I/O operation has been examined with the standard function 10result. 3) You are trying to write to the logical device KB 0:. Execute.I/O ERROR MESSAGES o. The following contains explanations of all run-time error numbers. which is an output-only device.

You are trying to Write a record beyond 65535 to a defined file. Disk write error. Directory is full. 228 TURBO Pascal Language Manual . and there is no more room in the disk directory. Not allowed in direct mode. Record length mismatch. Error in numeric format.I/O ERROR MESSAGES 04 10 20 21 22 90 91 99 FO F1 F2 FF File not open. Unexpected end-of-file. Assign to std files not allowed. File disappeared. You are trying to access (with BlockRead or BlockWrite) a file without a previous Reset or Rewrite. Block Write. or Chain a file assigned to a logical device. 3) A Read or BlockRead is unable to read the next sector of a defined file. Disk full while attempting to expand a file. Something may be wrong with the file. Programs cannot be Executed or Chained from a program running in direct mode (Le. but also Read. and Flush. The record length of a file variable does not match the file you are trying to associate it with.2). An attempt was made to Close a file which was no longer present in the disk directory. e.g. Execute. Operation not allowed on a logical device. 2) An attempt was made to read beyond end-of-file on a defined file. This may occur with the output operations Write. and Close may cause this error. a program activated with a Run command while the Memory compiler option is set). The string read from a text file into a numeric variable does not conform to the proper numeric format (see section 4. because of an unexpected disk change. You are trying to Rewrite a file. Rename. 1) Physical end-of-file encountered before EOF-character (Ctrl-Z) when reading from a text file. You are trying to Erase. WriteLn. as they cause the write buffer to 'be flushed. File size overflow. ReadLn. or (in the case of BlockRead) you may be trying to read past physical EOF. Seek beyond end-of-file.

All characters are significant. The TURBO editor may be used to edit the TURBOMSG. You may define as few or as many constants as you need.OVR file. 15 in total. Appendix G lists the resulting messages in full.TRANSLATING ERROR MESSAGES J J. denoted by a ~ character in the following listing. When you translate the error messages. also leading and trailing blanks.26. disregarding the use of constants. starting with the error number and immediately followed by the message text. but would require 101 characters if written in clear text. MSG. Notice that the TURBO editor deletes all trailing blanks. TRANSLA TlNG ERROR MESSAGES 229 . The message text may consist of any characters and may include previously defined constant identifiers (control characters). to enter a Ctrl-A ( ~ A) into the file. and 27. As a good example of the use of constants. The first 24 lines of this file define a number of text constants for subsequent inclusion in the error message lines: a technique which drastically reduces the disk and memory requirements of the error messages. TRANSLATING ERROR MESSAGES The compiler error messages are collected in the file TURBO. Then define these as constants at the top of the file and include only the constant identifiers in subsequent message texts. The original message therefore does not use trailing blanks in any messages. Each constant is identified by a control character. Control characters appear dim on the screen (if it has any video attributes). i. you should find as many common denominators as possible. the restriction being only the number of control characters. The value of each constant is anything that follows on the same line. You may use these error messages. then A. hold down the (CONTROl) key and press first p. Control characters are entered with the Ctrl-P prefix. These messages are in English but may easily be translated into any other language as described in the following. consider errors 25. but they will require excessive space. The remaining lines each contain one error message.e. the relation between constants and error messages will probably be quite different from the English version listed here. These are defined exclusively by constant identifiers. Start therefore with writing each error mesage in full. When all messages are translated.

'~X 12BFXHN~X 13IX)~X 14END~X 150F~X 17THEN~X 18TO~O roWNTO~X 20Boolean~E~X 230 TURBO Pascal Language Manual ..1 Error Message File Usting J.efined ~Q ~R ~SString Ie out of range ~V variable ~W overf low ~x expected ~y type ~ [ Inval id ~] pOinter ~ITextfi ~U 01'.J.1 ~A ~B ~C ~D ~E Error Message File Listing are not allowed can not be constant does not expression identifier file here Ie ~F ~G ~H ~Klnteger ~LFi ~NIllegal ~O or match real ~PUnd. 02': '~x '~x '~x 03'. 04' ( '~x 05')'~X 06' =' ~X 07' : =' ~X 08' [ '~X 09'] '~X 10'. '~X 11' .

1 21 ~L~V~X 22~K~C~X 23~K~E~X 24~K~V~X 25~K~O~R~C~X 26~K~O~R~E~X 27~K~O~R~V~X 28Po int e r~V~ X 29Record~V~X 308 imple~Y~X 318imple~E~X 32~8~C~X 33~8~E~X 34~8~V~X 35~T~X 36Type~F~X 37Untyped~G~X 40~P label in preceding~y syntax error definitions 43Duplicate~F~O label 44Type mismatch 41Unknown~F~O 42~P~]~Y 45~C~U 46~C and CASE selector~Y~D~Q 470perand~Y(s)~D~Q 48~ operator [ resul t ~Y 49~[ ~8 length 50~8~C length~D~Q~Y subrange base~Y 52Lower bound > upper bound 53Reserved word 54~N assignment 55~8~C exceeds line 56Error in integer~C 57Error in~R~C 58~N character in~F 60~Cs~A~H 51~[ 61~Ls and~]s~A~H 62St ructured~Vs~A~H 63~Ts~A~H 64~Ts and untyped~Gs~A~H 65Untyped~Gs~A~H 66I/O~A 67~Ls must be~V parameters TRANSLATING ERROR MESSAGES 231 .Error Message File listing J.

1 Error Message File Usting 68~L components~B~Gs 69~[~Odering of fields 70Set base~Y~U 71~[ GOTO 72Label not within current block 73~P FORWARD procedure(s) 74INLINE error 75~N use of ABSOUITE 90~L not found 91Unexpected end of source 97Too many nested WITH's 98Memory~W 99Compi ler~W 232 TURBO Pascal Language Manual .J.

.I or I xor array-constant :: = (structured-constant { . reserved words are printed in boldface. actual-parameter :: = expression I variable adding-operator :: = + I . Means "or". e. TURBO SYNTAX The syntax of the TURBO Pascal language is presented here using the formalism known as the Backus-Naur Form. case-element} end I case expression of case-element { .g. case-element} otherwise statement { . I {} All other symbols are part of the language.: block and case -element. case-label} case-list :: = case-list-element {. case-list-element} case-list-element :: = constant I constant . constant case-statement :: = case expression of case-element { . Each syntactic construct is printed in italics. statement} end complemented-factor :: = signed-factor I not signed-factor component-type :: = type component-variable :: = indexed-variable I field-designator compound-statement :: = begin statement { . and not symbols of the TURBO Pascal language: . Enclose items which may be repeated zero or more times.: array and for. Means "is defined as".TURBO SYNTAX K K. The following symbols are metasymbols belonging to the BNF formalism.g. index-type} ] of component-type array-variable :: = variable assignment-statement :: = variable: = expression I function-identifier :: = expression base-type :: = simple-type block :: = declaration-part statement-part case-element :: = case-list :statement case -label :: = constant case-label-list :: = case-label { . statement } end conditional-statement :: = if-statement I case -statement constant :: = unsigned-number I sign unsigned-number I constant-identifier I sign constant-identifier I string TURBO SYNTAX 233 . e. structured-constant} ) array-type :: = array [index-type { .

for-statement :: = for control-variable: = for-list do statement formal-parameter-section :: = parameter-group I var parameter-group function-declaration :: function-heading block. declaration -section :: = label-declaration -part 1constant-definition -part 1type-definition-part 1variable-declaration-part 1 procedure -and -function -declaration -part digit :: 0 11 12 13 14 15 16 17 18 19 digit-sequence :: = digit {digit} empty:: = empty-statement :: = empty entire-variable :: = variable-identifier I typed-constant-identifier expression :: = simple -expression {relational-operator simple -expression} factor :: variable I unsigned-constant I (expression) 1 function -designator 1 set field-designator :: record-variable. function -designator :: function -identifier I function -identifer (actual-parameter { . field-identifier field-identifier :: = identifier field-list :: fixed-part I fixed-part.identifier} if-statement :: if expression then statement { else statement} index-type :: simple-type = = = = = = = = = = = = = = = 234 TURBO Pascal Language Manual .file -identifer } file-type :: file of type final-value :: = expression fixed-part :: = record-section { . function -identifier:: identifer goto -statement :: goto label hexCtigit :: digit I A I B I C I 0 I ElF hexdigit-sequence :: hexdigit {hexdigit } identifier :: letter {/etter-or-digit } -. I function identifier (formal-parameter-section { .K TURBO SYNTAX constant-definition-part :: = const constant-definition { . constant-definition} .formal-para meter-section } ) : result -type.. record-section} for-list :: = initial-value to final-value I initial-value downto final-value. constant-definition :: = untyped-constant-definition 1 typed -constant -definition constant-identifier :: identifier control-character :: = @ unsigned-integer IA character control-variable :: = variable-identifier declaration -part :: = {declaration -section} .. identifier-list :: = identifier { . variant-part I variant-part file-identifier :: = identifier file -identifier-list :: = empty I ( file -identifer { .actual-parameter} ) function -heading :: = function identifier: result-type.

field-identifier} : type record-type :: record field-list end record-variable :: = variable record-variable-list :: = record-variable { . procedure-heading :: = procedure identifier . record-variable} referenced-variable :: = pointer-variable ~ relational-operator :: = = I <> 1<= I> = I < I> I in repeat-statement :: repeat statement { . record-constant-element } ) record-constant-element :: field-identifier: structured-constant record-section :: empty I field-identifier { .TURBO SYNTAX K indexed-variable :: = array-variable [ expression { . = = = = = = = = = = TURBO SYNTAX 235 . label} . program-identifier :: = identifier record-constant :: = (record-constant-element { . I procedure identifier ( formal-parameter-section { . statement} until expression repetitive -statement :: = while -statement I repeat-statement I for-statement result-type :: type-identifier scalar-type :: (identifier { . actual-parameter} ) program-heading :: empty I program program-identifier file -identifier-list program :: = program-heading block.expression} ] initial-value :: = expression inline-list-element :: = unsigned-integer I constant-identifier I variable -identifier I location -counter-reference inline-statement :: = inlineinline-list-element { . procedure-or-function-declaration :: = procedure-declaration I function -declaration procedure-statement :: procedure-identifier Iprocedure-identifier ( actual-parameter { .inline-list-element } label :: = letter-or-digit {Ietter-or-digit } label-declaration -part :: = label label { . formal-parameter-section } ) . letter :: = A I B I C I DIE I FIG I H II I J I K I LIM I NIOIPIQIRISITIUIVIWIXIYIZI alblcidielflglhliljlkillmi nlolplqlrlsltlulvlwlxlylzl __ letter-or-digit :: = letter I digit location-counter-reference :: I • sign constant multiplying-operator :: = 1/ I div I mod I and Ishl Ishr parameter-group :: = identifier-list: type-identifier pointer-type :: = ~ type-identifier pointer-variable :: variable procedure-and-function-declaration-part :: = {procedure -or-function -declaration } procedure-declaration :: procedure-heading block. identifier} ) * =.

. type-identifier :: = identifier type ::= simple-type Istructured-type Ipointer-type typed-constant-identifier :: identifier unpacked-structured-type :: = string-type 1array-type 1record-type 1 set-type 1 file-type unsigned-constant :: = unsigned-number Istring 1constant-identifier 1 nil unsigned-integer :: = digit-sequence 1$ hexdigit-sequence unsigned-number :: = unsigned-integer 1unsigned-real unsigned-real :: = digit-sequence. digit-sequence E scale-factor 1 digit-sequence E scale-factor untyped-constant-definition :: identifier constant variable :: = entire-variable 1component-variable Ireferenced-variable =[ = = = = = =. expression set-type :: = set of base-type sign :: + 1signed-factor :: factor 1sign factor simple -expression :: = term {adding-operator term} simple-statement :: = assignment-statement Iprocedure-statement 1 goto -statement 1inline -statement 1empty-statement simple-type :: = scalar-type Isubrange-type 1type-identifier statement :: = simple-statement 1structured-statement statement-part :: = compound-statement string :: {string-element } string-element :: text-string 1 control-character string-type :: = string [ constant ] structured-constant :: = constant 1array-constant 1record-constant 1 set-constant structured-constant-definition :: = identifier: type = structured-constant structured-statement :: = compound-statement 1conditional-statement 1 repetitive -statement 1 with -statement structured-type :: = unpacked-structured-type 1 packed unpacked-structured-type subrange -type :: = constant . constant tag-field :: = empty 1field-identifier: term :: complemented-factor {multiplying-operator complemented-factor} text-string :: {character} • type-definition :: = identifier = type type -definition -part:: = type type -definition { .K TURBO SYNTAX scale -factor :: = digit-sequence 1sign digit-sequence set :: = [ {set-element} ] set-constant :: {set-constant-element } ] set-constant-element :: = constant 1constant . = = = 236 TURBO Pascal Language Manual . type -definition} . constant set-element :: = expression 1expression ... digit-sequence 1 digit-sequence.

variable-identifier :: = identifier variant :: = empty I case-label list : (field-list) variant-part :: = case tag-field type-identifier of variant { .TURBO SYNTAX K variable -declaration :: = identifier-list: type I identifier-list: type absolute constant variable-declaration-part :: = var variable-declaration { . variant } while -statement :: = while expression do statement with-statement :: = with record-variable-list do statement TURBO SYNTAX 237 . variable-declaration} .

K TURBO SYNTAX Notes: 238 TURBO Pascal Language Manual .

46 47 48 ( ) A B C D E F G H I 49 4A 4B 61 62 63 64 65 66 67 68 69 6A a b c d e f g h i j + . 41 42 43 44 45 u $ % 8e . - * J 4C 4D K L M 6B 6C 6D k 1 m n 0 46 47 48 2D 2E 2F / 0 1 2 3 4 5 6 7 8 9 : 4E 4F N 0 P 49 50 51 52 53 54 55 56 57 58 59 60 30 31 32 33 34 35 36 37 38 39 3A 3B 3C 3D 50 51 52 53 54 55 56 57 58 59 5A Q R S T U V W X Y Z [ 6E 6F 70 71 72 73 74 75 76 77 78 79 7A 7B P q r s t u v w x Y z { .ASCII TABLE L L. < 61 62 63 = > ? 3E 3F 5B 5C 5D 5E 5F \ ] ~ 7C 7D I } - 7E 7F DEL ASCII TABLE 239 . ASCII TABLE DED HEX CHAR DED HEX CHAR 32 33 34 35 36 37 38 39 40 20 DED HEX CHAR 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 40 @ DED HEX CHAR 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 III 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 60 0 00 ~@ NUL 1 01 ~A SOH 2 02 ~B STX 3 03 ~C EI'X 4 04 ~D EDT 5 05 ~E mQ 6 06 ~F ACK 7 07 ~G BEL 8 08 ~H BS 9 09 ~ I HI' 10 8A ~J LF 11 0B ~K VT 12 C:XJ ~L FF 13 0D ~M CR 14 0E ~N SO 15 0F ~O SI 16 10 ~p DLE 17 11 ~Q 001 18 12 ~R 002 19 13 ~S 003 20 14 ~T 004 21 15 ~U NAK 22 16 ~V 8YN 23 17 ~w ErE 24 18 ~X CAN 25 19 ~y :EM 26 lA ~z SUB 27 IB ~[ ESC 28 lC ~\ FS 29 ID ~] GS RS 30 IE 31 IF .US ~~ ~ SPC ! 41 42 43 44 45 21 22 23 24 25 26 27 28 29 2A 2B 2C .

L ASCII TABLE Notes: 240 TURBO Pascal Language Manual .

Do I need TURBO to run programs developed in TURBO Pascal? No.9 .CMD file. How many lines of code can the compiler handle. What do I do when I run out of space while compiling? Use the$1 directive and/or generate a . How many significant digits does TURBO support in floating point? 11.COM or . The object code. you can make a . What do I do when the compiler generates too much code? Read the appendicies about compiler switches and . How do I make a .CHN files. Is TURBO an interpreter like UCSD? No.COM or . then type C. HELP!! ! This appendix lists a number of the most commonly asked questions and their answers.CM D file. cannot exceed 64 KB. What do I do when I run out of space using the editor? Split your source code (see chapter 17 on include files).CMD file? Type 0 from the main menu. You have not installed TURBO for your systel'!1. Why do I get garbage on the screen when I start the TURBO editor. 0: A: 0: A: 0: A: 0: A: 0: A: 0: A: 0: A: 0: A: 0: A: 0: A: 0: A: How do I use the system? Please read the manual. What do I do if I run out of space anyway? Use the Chain facility described in sections A.1.HELP!!! M M.COM or . No limit.1 0 and B. however. specifically chapter 1 . it generates ultra-fast machine code. HELP!!! 241 .

How do I prevent that? Set the C compiler directive off: {$C-l. Q: A: Q: A: 242 TURBO Pascal Language Manual . I don't want Ctrl-C to stop my program.M HELP!!! Q: A: Why don't Eofand Eoln work? Set the B compiler directive off: {$B-l. Why do my recursive procedures not work? Set the A compiler directive off: {$A-l (CP/M-SO only). or Ctrl-S to stop screen output.

TERMINAL INSTALLATION

N

N.

TEIRMINAL DNSTAlLATOON

Before you use TURBO Pascal, it must be installed to your particular terminal, i.e. provided with information regarding control characters required for certain functions. This installation is easily performed using the program TlNST which is described in this chapter. After having made a work-copy, please store your distribution diskette safely away and work only on the copy. Now start the installation by typing TlNST at your terminal. Select Screen installation from the main menu. Depending on your version of TURBO Pascal, the installation proceeds as described in the following two sections.

N.1

IBM PC Display Selection

If you use TURBO Pascal without installation, the default screen set-up will be used. You may override this default by selecting another screen mode from this menu:

Choose one of the following displays: 0) 1) 2) 3) 4) 5) Default display mode Monochrome display Color display 80x25 Color display 40x25 b/w display 80x25 b/w display 40x25
~X

Which display Center no. or

to exit)

~

Figure N-1: IBM PC Screen Installation Menu Each time TURBO Pascal runs, the selected mode will be used, and you will return to the default mode on exit.

TERMINAL INS TA LLA TlON

243

N.2

Non-IBM PC Installation

N.2

Non-IBM PC Installation

A menu listing a number of popular terminals will appear, inviting you to choose one by entering its number:

Choose one of the following terminals:
1) 2) 3) 4) 5) 6) 7) 8) 9) 10) 11) 12) 13) 14)

ADDS 20/25/30 ADDS 40/60 ADDS Viewpoint-lA ADM 3A Ampex D80 ANSI Apple/graphics Hazeltine 1500 Hazeltine Esprit IBM PC CCP/M b/w IBM PC CCP/M color Kaypro 10 Kaypro II and 4 Lear-Siegler ADM-20

15) 16) 17) 18) 19) 20) 21) 22) 23) 24) 25) 26) 27) 28)

Lear-Siegler ADM-31 Liberty Morrow MOT-20 Otrona Attache Qume Soroc IQ-l20 Soroc new models Teletext 3000 Televideo 912/920/925 Visual 200 Wyse WY-100/200/300 Zenith None of the above Delete a definition

Which terminal? (Enter no. or ~x to exit):

Figure N-2: Terminal Installation Menu If your terminal is mentioned, just enter the corresponding number, and the installation is complete. Before installation is actually performed, you are asked the question: Do you want to modify the definition before installation? This allows you to modify one or more of the values being installed as described in the following. If you do not want to modify the terminal definition, just type N, and the installation completes by asking you the operating frequency of your CPU (see last item in this appendix). If your terminal is not on the menu, however, you must define the required values yourself. The values can most probably be found in the manual supplied with your terminal.

244

TURBO Pascal Language Manual

Non-IBM PC Installation

N.2

Enter the number corresponding to None of the above and answer the questions one by one as they appear on the screen. In the following, each command you may install is described in detail. Your terminal may not support all the commands that can be installed. If so, just pass the command not needed by typing RETURN in response to the prompt. If Delete line, Insert line, or Erase to end of line is not installed, these functions will be emulated in software, slowing screen performance somewhat. Commands may be entered either simply by pressing the appropriate keys or by entering the decimal or hexadecimal ASCII value of the command. If a command requires the two characters 'ESCAPE' and' =', may: either or Press first the Esc key, then the =. The entry will be ecchoed with appropriate labels, i.e. <ESC> =. Enter the decimal or hexadecimal values separated by spaces. H exadecimal values must be preceded by a dollar-sign. Enter e.g. 27 61 or $lB 61 or $lB $30 which are all equivalent.

The two methods cannot be mixed, i.e. once you have entered a non-numeric character, the rest of that command must be defined in that mode, and vise versa. A hyphen entered as the very first character is used to delete a command, and echoes the text Nothing.

Terminal type:

Enter the name of the terminal you are about to install. When you complete TlNST, the values will be stored, and the terminal name will appear on the initial list of terminals. If you later need to re-install TURBO Pascal to this terminal, you can do that by choosing it from the list.

TERMINAL INSTALLA TlON

245

N.2

Non-IBM PC Installation

Send an initialization string to the terminal? If you want to initialize your terminal when TURBO Pascal starts (e.g. to download commands to programmable function keys), you answer V for yes to this question. If not, just hit RETURN. If you answer V, you may choose between entering the command directly or defining a file name containing the command string. The latter is a good idea if the initialization string is long, as e.g. a string to program a number of function keys would be. Send a reset string to the terminal? Here, you may define a string to be sent to the terminal when TURBO Pascal terminates. The description of the initialization command above applies here. CURSOR LEAD-IN command: Cursor Lead-in is a special sequence of characters which tells your terminal that the following characters are an address on the screen on which the cursor should be placed. When you define this command, you are asked the following supplementary questions: CURSOR POSITIONING COMMAND to send between line and column: Some terminals need a command between the two numbers defining the row- and column cursor address. CURSOR POSITIONING COMMAND to send after line and column: Some terminals need a command after the two numbers defining the row- and column cursor address. Column first? Most terminals require the address on the format: first ROW, then COLUMN. If this is the case on your terminal, answer N. If your terminal wants COLUMN first, then ROW, then answerV. OFFSET to add to LINE Enter the number to add to the LINE (ROW) address.

246

TURBO Pascal Language Manual

Non-IBM PC Installation

N.2

OFFSET to add to COLUMN
Enter the number to add to the COLUM N address.

Binary address?
Most terminals need the cursor address sent on binary form. If that is true for your terminal, enter V. If your terminal expects the cursor address as ASCII digits, enter N. If so, you are asked the supplementary question:

2 or 3 ASCII digits?
Enter the number of digits in the cursor address for your terminal.

CLEAR SCREEN command:
Enter the command that will clear the entire contents of your screen, both foreground and background, if applicable.

Does CLEAR SCREEN also HOME cursor?
This is normally the case; if it is not so on your terminal, enter N, and define the cursor HOME command.

DELETE LINE command:
Enter the command that deletes the entire line at the cursor position.

INSERT LINE command:
Enter the command that inserts a line at the cursor position.

ERASE TO END OF LINE command:
Enter the command that erases the line at the cursor position from the cursor position through the right end of the line.

TERMINAL INSTALLA TlON

247

Installation data is also saved in the installation data file and the new terminal will appear on the terminal selection list when you run TlNST in future. then define the command that initiates the dim video here. DELETE. enter N. and INSERT (0-255 ms): Delay after ERASE TO END OF LINE and HIGHLIGHT On/Off (0-255 ms): Enter the delay in milliseconds required after the functions specified. If this command is defined. 248 TURBO Pascal Language Manual . When you enterV in response to this question. you are asked: Operating frequency of your microprocessor in M Hz (for delays): As the delays specified earlier are depending on the operating frequency of your CPU. Delay after CURSOR ADDRESS (0-255 ms): Delay after CLEAR. The installation is finished. The installation data you haver just entered will be included in the installation data file and appear on the terminal selection menu. the following question is asked: START OF 'NORMAL VIDEO' command: Define the command that sets the screen to show characters in 'normal' video. Number of rows (lines) on your screen: Enter the number of horizontal lines on your screen. you must define this value. Number of columns on your screen: Enter the number of vertical column positions on your screen.N. installation data is written to TURBO Pascal.6 ).2 Non-IBM PC Installation START OF 'LOW VIDEO' command: If your terminal supports different video intensities. RETURN means 0 (no delay). Is this definition correct? If you have made any errors in the definitions. You will then return to the terminal selection menu. and you return to the outer menu (see section 1. but installation will not be performed.

75 Array Constants. 41 SUBJECT INDEX 249 . 207 Assigning a value to a pointer. 132 Absolute variables.209 BEFORE USE. 153. 187 Basic Symbols. 148 Arrays. 132. 190 Arrays and Records. 116 Arccus tangent. 157. 51 . 55 Auto Indentation. 178 Absolute Code. 28 Bios function.208 BdosHL function. 53 Addr. 132.209 Bdos procedure.207 B 10ckWrite. 112. 30 BlockRead. 206 Absolute Address Functions. 165. 35 Auto tab on/off switch. 28 H ide/display block. 29 End block. 29 Delete block.209 Bios procedure. 75 Array of characters. 216 Absolute value. 39 Block. 37 BDOS. 28 Copy block. 154. 132. 16 r. 37 Byte. 112. 176 A-compiler directive. 29 Mark single word. 75. i 07 Backup. 178. 207 Boolean. 1 6 Basic Data Types. 170 Abort command. 29 Read block from disk. SUBJECT ONDtEX A A Note on Control Characters. 28 Move block.209 Allocating Variables (New). 154. 21 A-command. 94.145 Bdos function. 121 Block Commands. 153. 206 Arithmetic functions. 193 Assign. 153. 144. 147. 90 Array Definition. 29 Write block to disk. 34 Abs. 181 Assignment operator.177 Adding operators. 37 Assignment Statement. 5 Begin block. 109 Array Subscript Optimization. 42 Brackets. 31 18 Backspace. 206 Array component. 154. 132 ArcTan. 146.209 Blanks.SUBJECT INDEX o o.208 BiosHL function. 175. 28 Begin block.AK files. 161.

132 CP/M Function Calls. 149. 216 8: I/O device selection. 216 X: Array optimization. 48 Constants typed.23 Ctrl-A in search strings. 121 Case statement. 107. 10. 149.23 TURBO Pascal Language Manual 250 . 208 Close. 32 Ctrl-C. 143. 216 CP/M -86/ MS-DOS / PC-DOS Compiler Directives. 16. 23 Character right. 183 Common features. 207 ClrEol.76. 46 in include files. 114. 207 Chain and Execute. 123. 208 Code segment. 206 Cosine.216 Compiler error messages. 90 Character Arrays.45 Control character prefix. 176 Conditional Statements. 18 Comment. 31. 216 CPU stack. 215 Ctrl-D. 215 V: Type checking. 214. 214 K: stack check. 1 28. 208 Cseg. 89 Control character. 166 Compilation To Disk. 29 Cos. 132. 214 I: I/O error handling.206 ClrScr. 208 Crtlnit. 214 Common data. 195 CR as numeric input. 57 Concat. 216 R: Range checking. 73 Chr. 127. 5 Compiler Directives. 221 compiler Options. 127.214 8: input/output mode selection.45 Common Compiler Directives.182 Char. 37. 182. 58 Chain. 174 Call by reference. 42 Character array constants. 34 Conversion.207 Copy block. 135. 170. 23 Characters. 71. 127. 175 Col(umn) indicator in editor. 73. 143. 65 Copy.214 I: Include. 77 Character left. 173 Compilation in Memory.207 Concatenation. 122 Call by value. 142 A: Absolute code.a SUBJECT INDEX C C-command. 173 Compound Statement. 15. 141 I: include files. 39. 170. 96. 57 Constant Definition Part. 67 Concurrent CP/M.178 Ctrl-A.32. 104 C: control character interpret. 148. 31. 215 W: With statement nesting. 150. 107 CrtExit. 153 CP/M-80 Compiler Directives. 21. 65.215 U: user interrupt. 16 Compiler Directive Defaults. 167 Compile Command. 17. 71.

24 Page up. 147. 128. 25 To right on line. 27 Delete left character. 23 Page down. 83 Disk change. 23 Line up. 65. 115 DEL.23 Ctrl-F. 27 Delete commands. 26 To left on line. 25 To top offile.179 Dynamic variables. 27 Delete to end of line. 175 Data Structures. 180 Directory Command. 29 Delete character under cursor. 162.SUBJECT INDEX o lI) D-command. 26 Ctrl-O Ctrl-R. 17 Discriminated unions. 28 Delimiters. 106 Data segment. 37. 21 Character left. 25 Ctrl-O Ctrl-X. 37 Direct memory access. 115. 33. 25 Ctrl-O Ctrl-P. 25 To top of screen. 17. 23 Line down. 208 Deviations from standard Pascal. 25 Ctrl-O Ctrl-C. 219 Ctrl-E. 23. 25 To last position. 179 Direct port access. 27 Delete right word. 148. 25 Ctrl-O Ctrl-E.58. 25 Ctrl-R. 107 Ctrl-Z. 189 Data transfer between programs. 39 DelLine. 161. 23 SUBJECT INDEX 251 . 128. 25 Ctrl-O Ctrl-S. 27 Delete character under cursor.23 Ctrl-X. 25 To bottom of screen.24 Cursor Movement.208 Delete. 190 Disk-reset. 23 To beginning of block. 24 Scroll up. 25 To end of file. 183 Declaration Part. 24 Scroll down. 25 Word left.23 Ctrl-W.89. 25 Ctrl-O Ctrl-D. 14 Dseg.67. 23 Word right.219 Digits.23 Ctrl-Q Ctrl-B. 25 To end of block. 1 50. 245 Delete block.24 Ctrl-S. 47 Declared scalar types. 175 Data conversion. 207 Delete a command. 25 Ctrl-O Ctrl-K. 27 Delete line. 69. 34 Cursor Movement Commands. 41 Defining a Pointer Variable. 23 Character right. 47 48. 14 Disk Files. 107 Delay.

26 Overwrite. 113. 229 Error messages Compiler. 96. 25 To end of file. 207 eXecute Command.18 File name. 104 of CR. 24 Scroll up. 230 Error message translation.227 run-time. 25 To top of screen. 96 Exp. 1 External procedures. 145 End block. 24 Scroll down. 168 Exist function. 23 Page down.97. 25 Word left. 106. 25 To bottom of screen. 23 Word right. 207 Error Message File Listing. 17 Execution error messages. 28 End Edit. 16. 18 Element (of set). 18 Col. 25 To top of file. 19 Insert. 133 Extended File Size. 102. 182.o SUBJECT INDEX E E-command. 56 End Address. 101 Eoln. 26 To left on line. 19 Line. 206 Exponential. 149. 200 Extensions. 23 Line up. 162. 107 Editor. 225 Execution in Memory. 9. 225 Execute.107. 25 To right on line. 19 Indent. 25 To end of block. 58 Empty Statement. 191 External Subprograms. 145 Echo. 24 Page up. 85 Else statement.108 Edit Command. 19 Character left. 16 Edit modes Insert. 26 Editing commands. 133. 30 End of line. 149. 167 Execution of A Program File. 23 To beginning of block. 221 1/0. 23 Character right. 207 Erase. 23 Editing of input. 23 Line down. 181 252 TURBO Pascal Language Manual . 25 To last position. 106. 35 End edit command. 39 EOF.207 EOF with text files. 107. 107.

92 Field list. 106 IBM PC Display Selection. 15 Indent indicator in editor. 200 Flush with text files. 133 Free memory. 129. 133. 196. 119. 104 I/O Procedures and Functions.208 !HI H-command. 128 o 1/0. 152. 176 False. 122 File pointer. 14 File of Byte. 130 G Get and Put. 31 Find and replace. 145. 95. 79 File handling routines. 19 File names. 8 Identifiers. 208 Heap.201 Function Declaration. 209 Hide/display block. 174 Halt procedure. 57 In-line M'achine Code.207 FileSize with text files. 194 Functions.106 I/O checking. 229 Forward References. 128. 56. 93 File Type Definition. 114 I/O error messages. 227 I/O mode selection. 102. 101 FillChar.208 Find. 43 If statement. 143. 1 68. 200 File parameters. 97. 165. 175.136 Hi function. 93 FilePos. 6 FileSize. 176 Free Unions. 93 File Standard Functions. 138 Frac. 83 Function Calls. 205 I/O to textfiles. 198. 89 Input without echo. 207 Files On The Distribution Disk. 92. 32 Find Runtime Error. 194 Hi. 113. 19 Indentation.170. 219 GetMem. 42 Field constants. 206 Fractional part. 116.194 Heap Control Procedures and Functions. 60 Foreign languages.220 GotoXY. 97. 170. 243 IBM PC Screen Installation. 208 H eapPtr.SUBJECT INDEX o f F-command. 4 Initialized variables. 113. 104 SUBJECT INDEX 253 . 176 Flush. 130 Function Designators. 93 File Interface Blocks. 114 I/O error handling. 207 File identifier.208 Goto Statement.202 File name indicator in editor. 97 File type. 54 Function Results. 29 Highlighting. 31 in this manual. 13 Home position. 101 For statement. 145. 79 Fields. 175. 159. 184 Include compiler directive.

133. 35 Line up. 152. 200 LongFileSize. 31 Line down. 9 Int.185 Logarithm. 200 Lower case. 208 K KeyPressed. 133 Logged Drive Selection.a Input characters. 209 SUBJECT INDEX L L-command. 72. 102 LongFilePos. 41 Integer part. 56 Large programs. 207 Insert and Delete Commands. 107 Insert.14 I Label Declaration Part. 1 8 Line Restore. 208 Installation. 106 editing. 128. 157. 43 LowVideo. 69. 136. 23 Line indicator in editor. 114. 156. 209 Local variables as var-parameters. 206 Lo. 27 Insert mode on/off switch.206 Integer. 27 I nsert indicator in editor. 186 Intersection. 219 Location counter reference. 1 IOresult. 207 Length of strings. 26 Insert commands. 19 Insert line. 186 Introduction. 14 Logical Devices. 107 strings. 133.200 LongSeek. 85 Line break. 23 Ln. 107 numeric values. 67 Letters. 26 InsLine. 129. 85 Intr. 48 Labels.43 Integer overflow. 141 Length. 136. 8 Installation of Editing Commands. 209 254 TURBO Pascal Language Manual . 187 Interrupt Handling. 37 Limitations on sets. 133 Internal Data Formats. 41.

16 W-command. 4 Mark and Release. 51 Options. 179 MemAvail. 116. 33 Restore line. 166 Menu C-command. 1 74 Main File Selection. 180. 143.178 Oops. 9. 81. 34 Auto tab on/off. 200 Operations on Text Files. 31 Control character prefix. 129. 31 Find and replace. 85 Memory / Com file / cHn-file. 134. 143.208 Not. 51.14 M -command. 107 0 O-command.16 L-command. 15. 173 SUBJECT INDEX 255 . 147. 29 Multi-user system.208 Move block. 143. 51. 176 MemArray. 166 Memory Maps. 133 Nesting of With statements. 31 Tab. 17 Minimum Code Segment Size. 147. 16 D-command.SUBJECT INDEX 0 ri\JiJ M -command. 173 Q-command. 173. 28. 181 Odd. 208 Member (of se!). 129. 30 Miscellaneous Procedures and Functions. 34 Maximum Free Dynamic Memory. 175 Miscellaneous editing commands Abort command. 15 O-command. 16 S-command. 30 Find. 3'1 Operations on Files. 206 Ofs. 100 Operator precedence. 179 Memory Management. 94. 32 Repeat last find.174 Memory access.17 R -command. 76 Multiplying operators. 51 Operators. 175 Obtaining the value of a pointer. 148.52 Numbers. 52 N Natural logarithm.148 New. 175 Minimum Free Dynamic Memory. 116 Mark single word.14 X-command.208 Nil. 175 Minimum Data Segment Size. 34 End edit. 208 Move. 143. 91 Multidimensional Arrays.116 Non-IBM PC Screen Installation.17 E-command. 15 Margins in this manual. 117. 244 NormVideo. 95 Multidimensional Array Constants. 43 Numeric input. 143.

92 Pointer Values. 148. 199.132. 95 Str. 162. 70 Write. 180 Pointers. 175. 72.208 Ordinal value. 94 Seek. 125 Rename. 143. 77. 17 Quit Command.16 Random. 26 SUBJECT INDEX p Packed Variables. 123 Pointer Related Items. 149. 29 Read Procedure. 208 Random access files. 180 Pointer symbol. 145. 96 Delete. 149 Port access. 96 Reset. 39 Ptr. 180 Pos. 135 Overflow integer. 206 Predecessor. 47 Program lines. 147. 24 Page Procedure. 42 Overwrite/insert. 101 Pred. 106. 174 O-command. 174 I-command. 94 Close. 102. 176 H -command. 108.o Options menu C-command.70 Val. 95. 69 Erase. 143. 191 value. 148. 136 Randomize. 121 Procedures. 176 Parameters.205 Read without echo.175 E-command.175 S-command. 121.204 Random(Num). 96 Flush. 115. 207 Position with text files. 94 Rewrite. 220 Page down. 174 D-command. 17 R R-command. 95 recursive. 95 Program Heading. 129.144 Ord. 180. 148. 179 Procedural Parameters. 220 Page up. 134 Predefined Arrays. 56. 208 Range Checking. 122. 208 Q Q-command. 11 5 Pointer types. 220 Procedure and Function Declaration Part. 160. 136. 134. 1 80 Port Array. 162. 41 real. 65 Read block from disk. 180. 42 TURBO Pascal Language Manual 256 . 132. 95 Insert. 176 M-command. 149. 143. 125 Assign. 50 Procedure Declaratron. 135.206. 164.145 F-command. 24 Paragraph. 205 Real overflow. 193 Pointers and Integers. 125 Procedure Statement. 69 Read. 189. 175. 121 variable. 104 Readln Procedure.

96 Rename procedure. 133 SizeOf. 76 S S-command.193 Set Assignments. 157. 42. 65. 164. 189. 219 Relational operators. 119 Special symbols. 73. 16 Scalar functions. 190 RecurPtr. 133. 207 Repeat last find. 24 Scroll up. 187. 175 Round. 157. 206 Square. 188.107 Run Command. 61 Repetitive Statements. 1 68. 134. 134. 37 Sqr.209 Space Allocation.206 RUBOUT. 170 Standard Files. 207 Restore line. 16 Run-time error messages. 33 Repeat Statement.206 Sine. 134. 103 SUBJECT INDEX 257 . 107 Retype.178 Set158. 91 Record Definition. 51. 37 Reset. 85 Set Operators. 88 Set Constants.44. 95. 94.53 Relative complement. 207 Root program. 85 Relaxations on Parameter Type Checking. 101 Seg. 163. 87 Set Type Definition. 31 RETURN. 208 Rename. 16. 135. 170 Recursion Local variables as var-parameters. 170 Recursion. 49 of labels. 219 Recursion stack. 59 Reserved Words. 125. 170.216. 94. 55 Sin. 208 Scroll down. 31 Seek. 183 Simple Statements. 193 Record Constants. 113. 23 Search. 137. 123 Release procedure. 125 Scope of identifiers. 193 Scope.SUBJECT INDEX o Reals. 92 Set Constructors. 175 StackPtr. 134 Sseg. 86 Set operations. 150. 65 Rewrite. 206 Sqrt.179 Stack. 134 Square root. 1 68. 225 Run-time range checking. 86 Set Expressions.207 with text files. 161. 144 Save Command. 63 Scalars. 79 Record type. 37. 56 Screen Related Procedures. 79 Records. 85 Shared data. 206 Scalar Type. 163.

136 MemAvail. 128 Intr. 153 Bios. 132 Addr. 201 SUBJECT INDEX Standard Procedures. 67 String Expressions. 68 String concatenation. 134 Swap. 135 UpCase. 127 Delay. 129 Randomize. 44. 55 Statement-separator. 38. 133 FilePos. 90 TURBO Pascal Language Manual 258 .117 Odd. 128 DelUne. 41 Start Address.127 ClrScr. 136 Random(NumL 136 Round. 128 InsUne. 127 CrtExit.135 Seg.116 NormVideo. 127 Bdos. 67 String Procedures. 113 FileSize. 154 BiosHL. 158. 114 KeyPressed.136 Int. 67 String Functions. 129 Read.193 Strings and Characters. 106 Seek.154 Chr. 149. 179 Succ. 133 Hi. 129 New.o Standard Functions. 164. 132 Abs. 136 Ln. 55 Static variables. 70. 57 Structured Typed Constants. 128 Crtlnit. 178 Ord. 67 Strings. 115 Str. 135. 178 ArcTan. 188. 135 Cos. 153 Bios. 146. 69 String Procedures and Functions. 137 Standard Identifiers. 182 CirEoI. 128 Execute. 207 String Assignment. 129 Move.134 Ofs. 73 String manipulation. 178 Dseg. 178 Sin. 207 String Type Definition. 149. 186 LowVideo. 132 Bdos. 7 Statement Part.133 SizeOf.133 IOresult. 182 FillChar.133 LO. 196. 50.113 Standard scalar types.134 Ptr. 137 Trunc. 129 GotoXY. 113 Frac.113 Exp. 179 EOF. 147. 134 Sqrt. 180 Random. 132 Cseg. 134 Sseg. 144 Starting TURBO Pascal. 177. 71 String indexing.137 Sqr. 180 Pred. 149. 149. 73 Structured Statement~. 154 Chain.

207 Value Parameters. 42 Trunc. 137. 49. 109 Write Procedure. 109. 146. 25 To end of block. 162. 191 The empty set.192 Variables.145 Trailing blanks. 122.209 T Tab. 83. 25 To end of file.206 Translation of error messages. 25 TPA. 106 Text Files. 117 V Val. 49 219 Variable Parameters. 135. 34 Transfer functions. 64 Succ. 123. 95 Write block to disk. 25 To top of screen. 192 Variable Declaration Part. 85 Unstructured Typed Constants. 111. 30. 51 Unclusion. 14 Write. 163. 134 Swap. 229 True. 155. 25. 35 Tag field. 43 Upper left corner of screen. 30 Write parameters. 148.59 Subrange Type. 61 With Statement. 206 Successor. 89 Untyped Variable Parameters. 25 To bottom of screen. 132. 65 Type Definition Part. 135. 81. 121. 128 User Writte n I/O Drive rs. 100. 205 Writeln Procedure. 70. 49 Typed constants. 25 To last position. 201 Using Files.163. 23 Word right. 134. 82 Terminal installation. 9 Text File Input and Output. 25 To right on line. 132.206 Type checking. 26 To left on line. 9 Work File Selection. 180 Word left. 205 IUl Unary minus.209 Upper case. 89 Untyped Files.SUBJECT INDEX 0 Sub-program.87 Unions. 97 Using Pointers. 115 absolute. 177 Variant Records. 123 Type Conversion. 123 UpCase. 25 To top of file. 121 Subrange. 196. 14 While statement. 137. 23 WordStar compatibility. 86 To beginning of block. 82 W W -command. 17 259 . 112 SUBJECT INDEX )( X -command.

.

.

orders . California 95066 .S.S.95 (plus $5 shipping and handling for U. Perfect for databases.. Available for you now with commented source code. 1984 To Order TURBO TOOLBOX© $49.. Mail check.TURBO TOOLBOX© POWERTOOLS FOR TURBO PASCAL We've crafted some special tools to help you create the best Pascal programs in the least amount of time. Designed to compliment the power and speed of Turbo Pascal. GINST (General Installation Program) Now . VISA or MASTERCARD number and expiration date to: D) BORlAnD . $15 shipping and handling outside U.. money order.) (California residents add 6% sales tax). the programs you write with Turbo Pascal can have a terminal installation module just like Turbo's! Saves hours of work and research. Turbo Toolbox © Available May. Source code included!!! Quicksort on Disk The fastest way to sort. B + Trees on Disk The fastest way to implement searches in records. these are functioning modules created to save you from the "rewriting the wheel" syndrome.)) INTERNATIONAL 4113 Scotts Valley Drive Scotts Valley.. and adds tremendous value to everything you write. And on disk means you won't be cluttering RAM. Preferred by knowledgeable professionals. address books or any other applications where you need to search through information for data.

You're Reading a Free Preview

Download
scribd
/*********** DO NOT ALTER ANYTHING BELOW THIS LINE ! ************/ var s_code=s.t();if(s_code)document.write(s_code)//-->