Alpha Micro AlphaPascal software User guide
જાહેરાત
જાહેરાત
SOFTWARE IV1ANUAL
AIphaPASCAL
USEWS GUOE ov/rA 00100 08
REV 801 alpha micro
ALPHA PASCAL USERS MANUAL
NOTE:
This printing of the manual, contains the contents of
Change Page Packet ill for the
AIphaPASCAL
Users
Manual',
(OSS"1OOO01O), which
Micro,
may be orff7Tsepa7tetyfrALpa
First Print mg:
1
August 1981)
Second Printing: 30 April 1981
Page ii
Alpha Micro', 'AMOS', 'ALohaBASIC,
AM'1OO'
'AIphaPASCAL', 'AlphaLlSP', and 'ALphaSERV' are trademarks of
ALPHA MICROSYSTEMS
Irvine, CA
92714
C'2.M 10/81
This book refLects AIphaPASCAL Versions 2,1) and later,
©1981 " ALPHA MICROSYSTEMS
ALPHA MICROSYSTEMS
17881 Sky Park North
Irvine, CA
92714
0.
0
ALPHA PASCAL USER'S MANUAL
Page iii
CHAPTER 1
CHAPTER 2
PART I
CHAPTER 3
CHAPTER 4
Table of Contents
INTRODUCTION
1.1
1.2
1.3
ORGANIZATION OF THIS BOOK
PASCAL BIBLIOGRAPHY
GRAPHICS CONVENTIONS USED IN THIS BOOK
GETTING STARTED
2.1
2.2
2.3
WHAT IS PASCAL'
SAMPLE PROGRAM
BRIEF DEMONSTRATION
2.3.1
Building a Pascal Program
2.3.1.1
The VUE Text Editor
2.3.2
Compiling and Linking a
Pascal Program
2.3.3
Running a Pascal Program
THE ALPHA PASCAL SYSTEM
COMPATIBILITY AND CONVERSION
3.1
3.2
3.3
PREVIOUS VERSIONS OF ALPHA PASCAL
STANDARD PASCAL
MAKING PROGRAMS COMPATIBLE WITH
THE
NEW
ALPHA PASCAL
OPERATING INSTRUCTIONS AND CHARACTERISTICS
4.1
FILE AND MEMORY REQUIREMENTS
4.1.1
4.1.2
File Extensions
File Search Pattern
4.1.3
Program Restrictions •0•S
4.1.4
Memory Requirements
4.2
CREATING A PASCAL PROGRAM.
4,3
THE ALPHA PASCAL COMPItER,
4.3.1
4.3.2
The Diagnostic Display
Compiter Options
4.3.2.1
The
IGTO Options
($G+ and $G—)
4.3.2.2
The Include Option (SI)
4.3.2.3
The List Options
(SL, SL+ and SL—)
4.3.2.4
The Page Option (SP)
4.3.2.5
The Quiet Options
($Q+ and SO—)
1—2
1—3
1—3
2—1
2—3
2—4
2—4
2—4
2—7
2—8
3—1
3—6
3—7
4—2
4—2
4—3
4—4
4—4
4—5
4—5
4—6
4—7
4—7
4—7
4—8
4—10
4—10
ALPHA PASCAL USER'S MANUAL
4.3.2.6
The Range Check Options
($R— and $R+)
4.4 'THE ALPHA PASCAL LINKER
4.4.1
Linking a New .PCF File
4.4.2
Replacing a .PCF File
4.4.3
Updating a .PCF File
4.4.4
Linking Assembly Language Subroutines
4.4.5
(the /LINK Option)
Preventing Backtracing of .PCF Files
(the /SMASH Option)
4.5
4.6
THE ALPHA PASCAL RUN—TIME PACKAGE
4.5.1
Library Version Checking
4.5.2
Interrupting a Program
HELPFUL COMMAND FILES
4.6.1
4.6.2
CompiLing a Single File (PC.DO)
Linking a Single File (PL.DO)
4.6.3
Compiling and Linking a Single File (PCL.DO)
4.6.4
Updatinq a Single Program
4.6.5
Module (PU.DO)
CompiLing and Updating a Single
Program Module (PCU.DO)
4—10
4—11
4—12
4—13
4—14
4—15
4—16
4—17
4—17
4—10
4—20
4—20
4—21
4—21
4—21
4—22
PART II
CHAPTER 5
CHAPTER 6
SUMMARY OF ALPHA PASCAL
GENERAL INFORMATION
5.1
BASIC STRUCTURE OF A PROGRAM
5.2
COMPOUND STATEMENTS (BEGIN AND. END)
5.3
COMMENTS
5.4
LEGAL IDENTIFIERS
5.4.1
Reserved Words
5.4.2
Standard Identifiers
5.5
5.6
SCOPE OF IDENTIFIERS
NOTATION
5.6.1
NUMBERS
5.6.2
STRINGS
DECLARATIONS AND DEFINITIONS
6.1
6.2
6.3
6.4
6.5
6.6
PROGRAM DECLARATIONS
LABEL DECLARATIONS
CONSTANT DEFINITIONS
TYPE DECLARATIONS
VARIABLE DECLARATIONS
FUNCTION AND PROCEDURE DECLARATIONS
6.6.1
Functions
6.6.2
Procedures
6.6.3
Forward Declarations s_i
5—3
5—4
5—5
5—6
5—6
5—?
5—9
5—9
5—10
6—1
6—2
6—4
6—4
6—5
6—6
6—6
6—8
6—9
4
1
.
.-.
V
ALPHA PASCAL USER'S MANUAL
CHAPTER 7
CHAPTER 8
CHAPTER 9
6.7
6.6.4
Formal Parameters
6.6.4.1
Value Parameters
6.6.4.2
Reference Parameters
EXTERNAL DECLARATIONS
DATA TYPES
7.1
7.2
SIMPLE DATA TYPES
7 .1..1
INTEGER t.i.z
REAL
7.1.3
BOOLEAN
7.1.4
CHAR
7.1.5
User—Defined Scatar
7.1.6
User—DefIned Subrange
STRUCTURED DATA TYPES
7.2.1
Packed Data Types
7.2.2
ARRAY
7.2.2.1
7.2.3
STRING
Multi—dimensionat Arrays
7.2.4
TEXT
7.2.5
SET
7.2.6
FILE
7.2.7
RECORD
7.2.7.1
variant Parts
7.2.8
PoInter Type
EXPRESSIONS
8.1
8.2
8.3
8.4
8.5
OPERATORS
8.1.1
Operator Precedence
8.1.2
Assignment Operator
8.1.2.1
ModIfying Assignment
8.1.3
Operators
Arithmetic Operators
8.1.4
Retational Operators
8.1.5
Logical Operators
8.1.6
Set Operators
CSTANTS
VARIABLES
IF—THEN—ELSE EXPRESSIONS
CASE EXPRESSIONS
STATEMENTS
9.2
9.3
9.4
9.5
9.6
9.7
ASSIGNMENT STATEMENT
PROCEDURE CALLS
EXIT
GOTO STATEMENT
NULL STATEMENT
COMPOUND STATEMENT
CONDITIONAL STATEMENTS
9.7.1
IF—THEN
9.7.1.1
IF—THEN—ELSE
—
9—2
9—2
9—3
9—4
9—4
9—4
9—5
Page v
6—11
6—1,1
6—12
6—12
7—2
7—2
7—3
7—3
7—4
7—5
7—6
7—6
7—7
7—8
7—10
7—10
7—11
7—12
7—15
7—16
7—1 8
7—19
8—1
8—1
8—3
8—4
8—5
8—6
8—6
8—7
8—7
8—8
8—8
8—9
ALPHA
PASCAL USER'S MANUAL
CHAPTER 10
Page vi
9.7.2
CASE—OF
9.8
9.7.2.1
CASE—OF—ELSE
REPETITIVE STATEMENTS
9.8.1
WHILE—DO
9.8.2
REPEAT—UNTIL
9.8.3
FOR—DO
9.9
WITH—DO
9—6
9—7
9—8
9—8
9—8
9—9.
9—10
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
10.1
10.2
BASIC FUNCTIONS AND PROCEDURES
10—1
10.1.1
The File Window
EOF (End—of—file Funotion)
10—3
10.1.2
10—3
10.1.3
EOLN (End—of—line Furktion)
10.1.4
GET and PUT
10—4
10—5
10.1.4.1
GET
10.1.4.2
PUT
10.1.4.3
Sample Program Using la—s
10—6
GET and PUT
SPECIAL FUNCTIONS AND PROCEDURES
FOR FILE I/O
10—6
10.1.5
READ, READLN, WRITE, and WRITELN
....
10—7
10.1.5.1
READ
10—7
10.1.5.2
READLN
10—8
10.1.5.3
WRITE
10.1.5.4
WRITELN
10—9
10—9
10.1.5.5
10.1.6
PAGE
Formatting Output
10—10
10—13
10.1.7
RESET
10—13
10.1.8
REWRITE
10—13
10—14
10.2.1
Information on AMOS Files
10—14
10.2.1.1
Random Files
10—15
10.2.1.2
Sequential Files
10—15
10.2.1.3
Logical Records
10—16
10.2.1.4
Opening and
Setting Up Files
10—16
10.2.2
CLOSE
10—17
10.2.3
CREATE
10—18
10—19
10.2.4
ERASE
10.2.5
EXTENSION
10.2.6
FILESIZE
10.2.?
ESPEC
10.2.8
GETFILE
10.2.9
JOBDEV
10.2.10 JOBUSER
10.2.11 LOOKUP
10—19
10—20
10—21
10—22
10—23
10—24
10—24
10.2.12 OPEN
10.2.13 OPENI
10.2.14 OPENO
10.2.15 OPENR
10.2.16 PFILE
10—25
10—25
10—25
10—26
10—26
10.2.17 RADSO
10.2.18 RENAME
10—26
10—2?
I
,
'
ALPHA PASCAL USER'S MANUAL
•
10.2.19 SEEK .
10.2.20 SETFILE
10.3
SAMPLE PROQRAM TO DEMONSJRATE FILE HANDLING,
10.3.1
Sample'Run
10.3.2
The Program ....,.,
10.3.3
Program Organization
10.3.3.1
The, AMOS file NAMREC.INC
10.3.3.2
The AMOS file EMPREC.INC
10.3.3.3
The AMoS file FIND.PAS
Page vii
10—27
10—27
10—29
10—29
10—31
10—38
10—38
10—38
10—39
CHAPTER 11
MISCELLANEOUS FUNCTIONS AND PROCEDURES
11.1
BASIC FUNCTIONS' AND
111.1
CHR
11.1.2
KILCMD
11.1.3
MARK
11.1.4
NEW
11.1.5
ORD
11.1.6
PRED
11.1.7
RELEASE
11.1.8
SUCC
11.2
SPECIAL TERMINAL DISPLAY PROCEDURES
11.2.1
CHARMODE
11.2.2
CRT
11.2.2.1
Cursor Positioning
11.2.2.2
Extended Screen
Display Options
11.2.3
INCHARMODE
11.2.4
LtNEMODE
11—1
11—1
11—2
11—2
11—3
11—4
11—5
11—5
11—6
11—6
11—7
11—7
11—7
11—8
11—9
CHAPTER 12 MATHEMATICAL FUNCTIONS
12.1
TRIGONOMETRIC FUNCTIONS
12.1.1
COS(X)
12.1.2
12.1.3
12.1.4
12.1.5
12.1.6
SLN(X)
TAN(X)
ARCtOS(X)
ARCSIN(X)
ARCTAN(X)
12.2
HYPERBOL
12.2.1
12.2.2
12.2.3
12.2.4
IC TRIGONQMETRIC FUNCTIONS
COSH(X)
SINH(X)
TANH(X)
ARCCOSH(X)
12.2.5
12.2.6
ARC5INHçX)
ARC'TANH(X)
12.3
MISCELLANEOUS MATHEMATICAL FUNCTIONS
12.3.1
ABS(X)
12.3.2
EXP(X)
12.3.3
12.3.4
1?.3.5
12.3.6
EXPONENT(X)
FACTORIAL(X)
LN(X)
LOG(X)
12—1
12—1
12—1
12—1
12—2
12—2
12—2
12—2
12—2
12—2
12—2
12—3
12—3
12—3
12—3
12—3
12—3
12—4
12—4
12—4
12—4
(Changed 30 April 1981)
•
ALPHA PASCAL USER'S MANUAL
CHAPTER 13
Paee viii
12.3.7
000(X)
12.3.8
POWER(X,Y) .
•
12.3.9
PWROFTEN(X)
12.3.10 PWROFTWO(X)
12.3.11 RANDOMIZE
12.3.12 RND
12.3.13 ROUND(X)
12.3.14 SHIFT(X,Y)
12.3.15 SQR(X)
12.3.16 SQRT(X)
12.3.17 STR(X) and STR(X,a,b)
12.3.1 TRUNC(X)
12.4
SAMPLE PROGRAM TO PAD A I'SJMBER WITH LEADING
ZEROS
12—6
12—4
12—4
12—5
12—s
12—S
12—5
12—6
12—6
12—6
12—6
12—6
12—6
STRING AND CHARACTER ARRAY FUNCTIONS AND PROCEDURES
13.1
13.2
STRING INTRINSICS
13.1.1
CONCAT
13.1.2
COPY
13.1.3
DELETE
13.1.4
INSERT
13.1.5
LCS
13.1.6
LENGTH
13.1.7
P05
13.1.R
STRIP
13.1.9
UCS
13.1.10 VAL
CHARACTER ARRAY INSTRINSICS
13.2.1
FILLCHAR
13.2.2
MOVELEFT and MOVERIGHT
13.2.3
SCAN
11—2
13—2
13—2
13—3
13—4
13—4
13—5
13—5
13—6
13—6
13—6a
13—7
13 7
13—7
13—9
PART III
CHAPTER 14
ADVANCED PROGRAMMING ON THE ALPHA PASCAL SYSTEM
SYSTEMS FUNCTIONS AND PROCEDURES
14.1
LOCATION
14.2
SIZEOF
14.3
14.4
14.5
MEMAVAIL
MAINPROG
SPOOL
14.5.1
Switches
14.5.2
Error codes
14.5.3
Function definition
14.5.4
The SPOOL subroutine
14.6
XLOCI( AND GETLOCKS
14.6.1
The XLOCI( subroutine
14.6.2
14.6.3
Setting a lock
Setting a lock (and waiting until it is available)
.
14—1
14—1
14—2
14—2
14—3
14—3
14—4
14—4
14—4
14—5
14—6
14—7
14—7
(Changed 30 April 1981)
ALPHA PASCAL USER'S MANUAL
CHAPTER 15
CHAPTER 16
14.6.4
14.6.5
14.7
XMOUNT
14.8
14.9
14.10
Clearing a lock
The GETLOCKS subroutine
14.7.1
14.7.2
14.7.3
Error codes
Unmounting a disk
Error codes
14.7.3.1
MOUNTED
14.7.3.2
UNMOUNTED
14.7.3.3
DEVNOTFOUND
14.7.3.4
BADHASH
14.7.3.5
NOVOLID
TIME
TOD
ERROR HANDLING PROCEDURES AND VARIABLES
14.10.1
Including ERT.INC
14.10.2
ERRORTRAP
14.10.3
XERRORTRAP
14.10.4
ERROR
ASSEMBLY LANGUAGE SUBROUTINES
15.1
15.?
CALLING ASSEMBLY LANGUAGE SUBROUTINES
ARGUMENT PASSING CONVENTIONS
15.2.1
Argument Passing
15.2.2
Data Formats
15.2.2.1
CHAR
15.2.2.2
INTEGER
15.2.2.3
BOOLEAN
15.2.2.4
Subranqes and
Scalar Tyoes
15.2.2.5
REAL
15.2.2.6
STRING
15.2.2.7
Pointers
15.2.2.8
Sets
15.2.2.9
Arrays
15.2.2.10 Records
15.2.2.11 FiLes
15.2.3
Error Exit
15.3
CODE RESIDENCY
15.3.1
Routine, PLINKed with /LINK
15.4
15.5
15.3.2
Routines PLINKed without ILINK
OBTAINING MEMORY FOR DATA AREAS
RESTRICTIONS
WRITING AND MODIFYING AN EXTERNAL LIBRARY
16.1
16.2
16.3
16.4
STDLIB
WRITING LIBRARY FILES
MODIFYING S'TDLIB
VERSION CHECKING
Page ix
14—8
14—9
14—9
14—10
14—10
14—10
14—10
14—10
14—10
14—10
14—10
14—11
14—11
14—12
14—12
14—12
14—1 5
14—16
15—1
15—2
15—3
15—4
15—4
15—4
15—4
15—4
15—4
15—4
15—4
15—4
15—5
15—5
15—5
15—5
15—S
15—5
15—6
15—6
15—6
16—2
16—3
16—4
16—5
(Changed 30 April 1981)
ALPHA PASCAL USER'S
MANUAL
PART IV
APPENDIX A
APPENDIX 8
APPENDIX C
INDEX
APPENDICES
QUICK REFERENCE TO ALPHA PASCAL
A.1
PROGRAM STRUCTURE
A.2
DECLARATIONS AND DEFINITIONS
4.2.1
LabeL Declarations
A.2.2
4.2.1
Constant Definitions
Type Definitions
4.2.4
Variable DecLarations
A.2.5
Procedure Declarations
4.2.6
Function Declarations
A.3
DATA TYPES
A.3.l
Simple Data Types
A.3.l.l
Standard Data Types
A.3.l.2
Scatar Data Types
A.3.2
Structured Data Types
A.3.2.l
String
4.3.2.2
Arrays
A.3.2.3
Sets
A.3.2.4
File Type
A.3.2.5
Record Type
A.3.2.6
Pointer Data Types
A.4
EXPRESSIONS
A.4.l
Operators
A.4.1.l
Assignment
A.4.1.i.1
The Modifying
Assignment
A.4,.l.2
Operators
Arithmetic nperators•
A.4.1.3
Relational Operators
A.4.l.4
Logical Operators
4.4.1.5
Set Operators
A4.2
Constants
4.4.3
Variables
4.4.4
Function Calls
4.4.5
IF—THEN—ELSE and CASE—OF Constructs in Expressions
A.5
STATEMENTS
A.5.l
Simple Statements
A.S.l.l
Assignment Statement
4.5.1.2
Procedure CML
A.5.i.3
GOTO Statement
A.5..1.4
Null Statement
4.5.2
Structured Statements
A.5.2.l
Compound Statements
A.5.2.2
Conditional Statements
A.5.2.3
Repetitive Statements
4.5.2.4
WITH—DO Statements
A.6
ALPHA PASCAL STANDARD
FUNCTIONS AND PROCEDURES
THE ASCII CHARACTER SET
ALPHA PASCAL COMPILER ERROR MESSAGES
A—9
4—9
A—9
A—9
A—9
4—10
A—iC
4—10
A—1O
A—li
A—li
A—i
A—i
A—i
4—7
A—i
A—S
A—S
4—8
4—12
A—i
A—2
4—2
4—2
A—3
A—6
4—4
4—4
A—4
A—4
A—S
A—S
A—s
A—S
A—5
A—6
4—6
4—6
4—6
Page ,
CHAPTER
1
INTRODUCTION
This book is a reference manual for the AlphaPascal programming system,
We realize that some of you may be experienced PascaL programmers, whiLe others may never have seen a Pascal program before, range of
Therefore, to suit the wide interests and backgrounds our readers are LikeLy to have, we have tried to organize this book so that you can easily find the information that you need without spending unnecessary time on chapters that contain information that you already know or that is not important to you
(For information on the organization of this book, see Section Li, below,)
Because there are so many exceLLent books available that teach you how to program in Pascal, we have not attempted to do so in this book.
(For a of some of the books
BibLiography,")
list
that we found heLpfuL, see Section 1,2, "Pascal
However, our intention is to provide a detailed enough description of
AlphaPascal that an experienced computer programmer who is unfamiliar with Pascal can get some idea of how to write PascaL programs
The major purpose of the book is threefoLd:
1,
2,
To describe this impLementation of ALphaPascaL;
To discuss how this impLementation differs from previous versions of
AlphaPascal and from the standard Pascal as set forth in the
PascaL User Manual and Report by Jensen and
Wirth
(and to give hints on converting programs written in these versions of Pascal to the current AlphaPascal format); and
3.
To give operating runtime package.
instructions for the various components of the
ALphaPascai programming system: the compiler, the Linker, and the
This book aLso gives information to systems programmers on writing their own assembLy Language subroutines caLlabLe by Pascal programs, and on writing and modifying an externaL procedure library
INTRODUCTION
Page 1—2
1.1
ORGANIZATION OF THIS BOOK
Some of the chapters in programmers, while others this book are aimed at experienced
Pascal are specifically for new Pascal users.
To help you find the information that you are particularly interested divided this book into four general parts:
in,
we have
PART I
—
THE ALPHA PASCAL SYSTEM
PART II
—
SUMMARY OF ALPHA PASCAL
PART III —
ADVANCED PROGRAMMING ON THE ALPHA PASCAL
SYSTEM
PART IV
—
APPENDICES
The rest of this section discusses which chapters may be of particular interest to specific readers.
IF YOU ARE AN EXPERIENCED PASCAL PROGRAMMER:
You wilt probably want to skip Chapter 2, "Getting
Started," and go directly to Chapter 3, "Compatibility and Conversion," which tells you how this version of
Pascal
differs
from
earlier
versions of
AlphaPascal and from the
Jensen and
Wirth standard.
Chapter discusses how
4 to operate the various components of the AlphaPascat programming system.
which give detailed
Rather than read through Chapters 5 discussions procedures, you may want merely
Reference to
AlphaPascal," to to get of turn an the AiphaPascat statements and to idea
Appendix of procedures included in this implementation of Pascal.
A, through
"A
13,
Quick the functions and
After you are somewhat familiar with the AlphaPascal system, you may want to read
Chapter 15, "Writing and Modifying an External Library
File." If you are a systems programmer, you may want to read Chapter
16, "Assembly Language Subroutines."
IF YOU ARE NEW TO PASCAL:
You gives a demonstration
Pascal program.
II,
will
probably want to read Chapter 2, "Getting Started," which
brief
"Summary of of discussion of
Pascal,
Next, you will probably want to start reading Part
AlphaPascal," for information about this version of the Pascal language.
and goes through a quick building, compiling, andt running a small, simple
When you are ready to begin writing
Pascal programs,
Chapter
4,
"Operating Instructions information on using the AlphaPascal and turn back
Characteristics,' compiler and run—time package.
to for
NOTE: We would appreciate any comments or
Comments Form in the back of this book.
suggestions; note the
Reader's
.
INTRODUCTION
Page 13
1,2
PASCAL BIBLIOGRAPHY
The most important source book definition of standard Pascal) is: for
Pascal programmers (containing the
Jensen, K, and Wirth, N,
PascaL User Manual and Report (Second
Springer'Verlag, 1976
Edition)
If you are interested, in Learning to program in Pascal, take a Look at one or more of the foLLowing textbooks: you might want to
Conway, R,, Gries, 0, and Zimmerman, E,C,
A Primer on Pascal
Winthrop, 1976
Grogono, P
Programming in Pascal
Addison"Wesley, 1978
Kieburtz, R,B,
Structured Programmi ngand
Prentice"Hall, mc,, 1978
ProbleirSolving with Pascal
Schneider, G,M,, Weingart, S,W,, and Perlman, D,M,
An Introduction to Programming and Problem Solving with Pascal
John Wiley g Sons,. 1978
Wilson, hR. and Addyman, A,M,
A Practical Approach to Pascal
Springer"Verlag, 1978
1,3
GRAPHICS CONVENTIONS USED IN THIS BOOK
The symbol indicates the place terminal carriage return key if you computer.
(The carriage return labeled RET or RETURN, and tells the
current line,)
in an example where you would press the were entering the example into the key on the terminal keyboard is usually computer to accept and process the
INTRODUCTION
Page 14
It
is often confusing when to determine which elements example, program programmer,
Looking at a program in a new computer Language are an inherent part statements) and which elements of the
Language follow these conventions:
(for sample programs
Reserved words are all upper case and underlined,
Standard identifiers are all upper case, but not underlined,
All are in user
identifiers
(for example, variable names, constants, etc.) a combination of upper and lower case, and are not underlined,
(Note that this manua underlining
will
try you and whi
I reserved words are underlined,
For deviates
claritys
sake, from the usual Alpha Micro documentation therefore, practice of
We to clearly indicate which portions of our examples are entered by ch portions are printed by the computer,)
-
CHAPTER
2
SETTING STARTED
This chapter is primarily for the benefit of the programmer who is interested in learning Pascal, but who has not yet had the chance to become familiar with the language.
If you are already familiar with Pascal, you wilt probably want to skip to Part I of this book, "The AlphaPascal System,' for information on Alpha Micro's specific implementation of Pascal, and for operating instructions for the AlphaPascal compiler.
(You may be interested in
SectIon 2.3
of this chapter, however, which contains a brief demonstration of creating, compiling, linking, and running a small Pascal program.)
The rest of this chapter gives a brief discussion of Pascal and walks you through a quick demønstration of building, compiling, linking, and running a program under the AlphaPascal system.
We also show you a small Pascal program and discuss its component parts.
2.1
WHAT IS PASCAL?
The Pascal language is based on the 1970 work of Jensen and Wirth, and is related to the ALGOL—family of languages.
Pascal is a fairly new programming language, and is considered by many to be
"cleaner" and more powerful in design than many older languages as welt as more reflective of structure.
current trends in the philosophy of program design and
However, this does not mean that programs written In Pascal will necessarily be clearer or more powerful than programs written in other languages—— that wiLl depend on thi programmer.
The major claim made for
Pascal is that the language makes it easier to write programs that may be easily understood and maintained.
It was developed in response to increasing concerns that current programming languages were not encouraging good programming "style," and is based on the idea that an effective programming language should help the programmer to apply design techniques in a natural and simple way. The result should be well—made, welt—structured programs that are easy to read and easy to
GETTING STARTED
Page 2—2 maintain. Because most of a program's life cycle is spent in design and maintenance, the creators of Pascal tried to develop a language that helps programmers In these areas.
Pascal's use, acceptance, and availability have become widespread in years.
An increasingly large number of students recent are being taught Pascal as their first programming language.
Pascal's use in Industry is also becoming more prevalent as project planners become more aware of implementing large programming projects.
its usefulness in
Some of Pascal's advantages stem from these characteristics:
*
Pascal encourages welt—structured programming by requiring that programs be built in a block structure in which the beginning and end of each procedure is clearly marked. Because program structure is hierarcHal in nature, programming in Pascal lends itself naturally to top—down design.
* One of the most extensibility.
It important features of Pascal is its is very simple to add your own functions and procedures if the routines provided by Pascal do not exactly match your needs.
In addition, on the AlpitaPascal system, you can add these user—defined routines to an external library where all
Pascal programmers can make use of them.
*
*
Pascal was designed to be a general—purpose language.
Since it is not specifically aimed at scientific or data processing applications, it can be used to solve a wide range of problems.
An important feature of Pascal is its powerful data structures
(arrays, sets, records, pointers, user—defined, etc.), and the sophisticated structures you can build from those primitives
(e.g., linked lists).
*
*
Any variable used in a program must be declared within that program.
That is, Pascal requires that the type of values that a variable may assume (e.g., integer or boolean) be clearly stated by the programmer.
This helps both in program design and maintenance, since the readability and organization of your program are enhanced.
Variables may be global or local in scope, depending on where they are declared.
Most implementations of Pascal, while they may include extensions to the language, also contain a subset of Pascal which adheres firmly to the standards for the language as set forth by Jensen and
Wirth.
This means that programs wrttten in standard Pascal are transportable between computer systems on which Pascal implemented.
is
.
Page 2—3
GETTING STARTED
2.2
SAMPLE PROGRAM
If you have never •before seen a PascaL program, you may be interested taking a look at the small, simpLe program below: in
(Determine what % is deducted from your gross salary)
PROGRAM Salary;
VAR
Gross, Takehome, Deductions, Percentage
BEGIN (Begin Program Salary)
REAL;
(Print ques.t1ons and read answers from terminal)
WRITE ('What is your•gross salary? ');
READLN (Gross);
WRITE ('What is your takehome salary? ');
READLN (Takehorne);
Deductions
:
Gross —
Takehome;
Percentage
:
1OO*theductio,s/Grpss);
WRITELN ('They keep', Percentage,
' percent of your salary!')
END (End Program Salary).
NOTE: To help you keeç track of which words in the program are eLements of the
Pascal language:and which are variab{e names and data supplied by you, we have written in upper case and underlined those words (calLed
"keywords") that are actually part of the Pascal language.
(Of course, you do not underline such keywords when you write your own Pascal programs.)
Those words that are in upper case, but that are not underlined, are called
"standard identifiers"; they are elements of the Pascal language which can be re—defined by you.
The words that are upper and lower case and that are not underLined in the example above are variable names, comments, and string data supplied by the writer of the program.
The first line of our sample program is catted a "comment."
It Is ignored by the computer, and has no effect on the execution of the program.
Its purpose
Is to make the program easier to read for humans.
(Comments in
Pascal are denoted by enclosing text either with the symbols "(*" and
"*)" or with the symbols "C" and ")".)
The second line "declares" the program name, "Salary."
The and
third
tine "declares" the variables "Gross," "Takehome," "Deductions,"
"Percentage," and tells Pascal that they can only assume the values of real numbers.
(For information on declaring programs and variables, see
Chapter 6, "Declarations and Definitions.")
The fourth line contains a
BEGIN statement; this statement marks the beginning of a program block.
The end of. this block (and in this case, the end of the program) is marked by the END statement on line 13.
Within this block, we send questions to the terminal display (sixth and eighth lines) and read data from the terminal keyboard (seventh and ninth tines).
On the tenth and eleventh lines we compute the answer we need based on the data we received from the user of the program.
The twelfth line sends the computed answer to the terminal display.
(For information on
Pascal program statements and procedures, see Part II, "Summary of AlphaPascat.")
GETTING STARTED
Page 2—4
(NOTE: So that mentioned our convenience only; the tines with numbers.) we could identify specific tines
identifiers
of the program
such as "first line" or "fourth line."
in Pascal programs do not to you, we
This was for
ordinarily
start
2.3
BRIEF DEMONSTRATION
Now that you've taken walk you through running the program.
a look at a small Pascal program, we would like to a brief demonstration of building, compiling, linking, and
We'll assume been assigned that the computer and your terminal are on, and that you have an account in which to work.
Make sure that you are at
AMOS command
level (that is, that
you see the prompt symbol, ".", that indicates that you are communicating with the operating system).
First, log into the system contains the account that account.
by typing
LOG followed by the device that you want to log into and then entering the number of
Then press the RETURN key on your terminal.
you want to work in account [20,33 on device DSKI:, enter:
For example,
if
LOG DSK1:[20,33 t!D
Now you see something like:
Logged into DSK1:[20,33
You can now begin to create your Pascal program.
2.3.1
Building a Pascal Program
To build a Pascal program, use one of the system text editors to create your program as a text file.
If you are using a video—display terminal, you will probably want to use the screen—oriented text editor, VUE, rather than the character—oriented text editor,
EDIT.
2.3.1.1
The VUE Text Editor versions exist of the program we're going, to create.
the disk any file called
—
First,
SALARY.PA5.
we'll
make sure that no
earlier
So, we'll erase from
At AMOS command level, enter:
If you see:
ERASE SALARY.,PAS
SALARY.PAS erased
Total of 1
file deleted, 2 disk blocks freed
GETTING STARTED:
Page 2—5 that it.
means that thefile did exist on the disk, and that we have now erased
If you see:
ZNo files erased no error occurred, it's just that no file named
SALARY.PAS
was in the account you are logged into, and so we couldn't erase it.
tn either case, you now are free to create a new file of the name SALARY.PAS.
So, enter:
VUE SALARY.PASt
Now VUE looks for the disk tile SALARY.PAS in the account you are loqqed into.
Since the file does not yet exist, WE says:
SALARY.PAS does not exist — create it?
Enter a V followed by a RETURN to tell VUE that you do want to create a new file named SALARV.PAS.
you see one or more tines of asterisks.
(If you do not see this display, but instead see a display whose first line begins: "AlphaVue n.n
Status:" (where n.n is the version number of VUE), simply type an
Escape
(sometimes labeled
ESC or ALT MODE on your keyboard), and VUE will display the asterisks.)
The display of asterisks means that you are in editing mode, and that VUE is ready for you to type your program in.
Start typtng the sample program in
Section 2.2
just as you would if xou were using a typewriter.
Type in the example exactly as shown, inctudln alt semicolons, quote marks, and parentheses.
If you make a mistake, you may erase single characters by using the RUB key
(sometimes labeled DEL. or DELETE).
To erase the characters on an entire line, type a
Control—RUB.
(That is, hoLd down the CONTROL key while you press the RUB key.)
The cursor (which may appear as a small white rectangle, triangle, tine, or other symbol) marks your place on the screen; the next character you type appears at the cursor position.
If more extensive corrections are needed, you may back up in the display by using the arrow—keys to move the cursor back and forth in the text on the screen.
(If your terminal does not have these arrow—keys, you must move the cursor by typing Control—J,
Control—H,
Control—K, and Control—L.
For example, to move the cursor to the left, hol4 down the CONTROL key and type an H.)
When the cursor is positioned just to the left of th!
error, you can overwrite the error by typing your new characters over the problem spot.
Or, if you do not want to overwrite the error, type a Control—Q.
From this point on, the new characters you type will be Inserted into the current line, rather than overwriting it.
(To resume overwriting characters, type another Control—Q.)
(Changed 30 April 1981)
GETTING STARTED
Page 2—6
Of course, there are many here.
more WE editing commands that we won't discuss
You can, for example, erase characters a word at a time, insert entire new lines of text, search for particular groups of characters, or move the cçirsQr a word at a time. For more information on usinq VIlE, see the
AIphaVUE User's Manual, (DWM—OO100—15),
When the program is entered correctly,
Escape.
prompt you are ready to leave VIlE.
Type an
The screen clears, and the cursor is now positioned next to the VIlE symbol, >
(You are now in command mode.) Type an F followed by a
RETURN.
This tells VUE that you are finished; it therefore writes your file
SALARY.PAS out to the disk.
Next you see the AMOS prompt symbol, a dot, which tells you that you have exited VIlE, and are now back at AMOS command level.
Here is a summary of the keys that you will use the most when editing programs with VIlE:
RETURN
End each line with a carriage return symbol by pressing the
RETURN key (sometimes labeled RET, CR, or CARRIAGE RETURN).
ESC
To change from editing mode to command mode (and back again), type an Escape by pressing the ESC key
(sometimes labeled ALT NODE or ESCAPE).
CONTROL
Most of the VUE commands are control—characters.
To type a control—character, hold down the
CONTROL key (sometimes labeled CTRL), and type the appropriate character.
example, to type a
For
Control—C, hold down the CONTROL key while you type a C.
RUB To delete a single character, press the RUB key
(sometimes labeled DELETE or DEL).
ARROW—KEY
To move the cursor around on the screen. use the keys marked with arrows (labeled with a left—arrow, right—arrow, up—arrow, and down—arrow).
For example, to move up on the screen, press the up—arrow key.
If your terminal does not have arrow keys, you will use these control—characters instead:
Control—H
Control—J
Control—K
Control—L
To move left
To move down
To move up
To move right
If
VIlE is new to you, you may want to ask the System Operator to place into your account a copy of the VIlE initialization file in which the menu—display option has been enabled.
VUE wilt then display a summary of its commands when you enter command mode.
You may also want to ask the System operator to modify the VIlE initialization file so that the default extension is set to .PAS (which means that VIlE wilt, expect you to edit .PAS files and thus will not require you to enter a file's extension unless you want to edit a non—.PAS file).
.
(Changed
30 Apri1 1981)
Page 2—7
GETTING STARTED:
2.3.2
CompIling and Linking a Pascal Program
The first step after creatinq your Drogram is to compile it using
CMPILR.
After you have compiled it, the program is still not ready to run until you use the linker, PLINK.
(Both PLINK and CMPILR are themselves programs written in
Pascal.) Chapter 4, "Operating Instructions and Characteristics," discusses the operation of PLINK and CMPILR in detail.
Fornow, we'll, simply show you one way to use them—— t* compile and link a new program made up of only one file.
For this demonstration, we will use one of the command files provided with your system, PCL.DO.
This command f:ite conDains a series of commands and data that automatically
invo
CMPILR and
PLINK far you, and provide necessary to those programs.
NOTE: Remember that the larger your memory
At
AMOS command level, enter PCL followed by the name of your program off the .PAS extension).
Then type a RETURN.
For examplel
(leaving
PCL SALARYtj
Now the PCL command file runs CMPILR and PLINK for you.
compiled, you see a display something like this:
As your program is
PRIJN CMPILR
AlphaPascal V2.O
Source file name? SALARY
Diagnostic file name (<return> for terminal)?
AlphaPascal Compiler Version 2.0
PROGRAM <
0>———
3>
12 lines
10.47 seconds, 68.79 lines/minute
No compilation errors.
If CMPILR spots an error while it is comotling your program (for example, if we left the semicolon off the end of the second line), CMPILR pauses, and tells you about the problem.
For example:
VAR
Gross, Takehome, Deductions, Percentage
:
REAL;
?Line 2: CINISOP]
;'
Hit
RETURN to continue or
')' expected
—— inserting
';
The message above tells us that a semicolon is missing in front of the symbol
VAR.
("(INISOP]" identifies the portion of the compiler that caught the error—— you can disregard that information.)
Now you may type a RETURN to resume program compilation, or you may command level.
type a
Control—C (hold down the CONTROL key while you type a C) to interrupt the compilation.
(If you type a
Control—C, CMPILR displays the message:
"?Compilation
aborted" and then returns you to AMOS command level.
If you type a RETURN, CMPILR resumes the compilation, and then returns you to
AMOS
In either case, because an error has occurred PCL does not go on to link the program and you are returned to AMOS command level.)
If CMPILR reported something other than "No compilation errors," your program is incorrect.
You should use VUE on the oroqram and check your copy
(Changed 30 April 1Q81)
GETTING STARTED
Page 2—8 of the program against use the
its options, refer
the one in this book.
PCI command file again.
also discusses the
(For full information
to Section 4.3, "The compiler display.)
Correct any discrepancieg, and on using CMPILR and
AlphaPascal Compiler."
That section
Let's say that invoke the intermediate files: program executable
still
tinker,
.pcr
your program has compiled without is not completely references within the intermediate file.
looks something like
PLINK.
this point,
The second part of the error.
CMPILR
PCL.DO goes
SALARY.Po1, SALARY.Po2, and
SALARY.p03.
this:
At ready to run.
files
and
PLINK wilt fully resolve
will
has,, created three
However, produce the on to
final,
screen display that you your see
.ERASE SALARY.PCF
ZNo files deleted
.PRIJN PLINK
Aiphapascal V2.O
Code file = SALARY
Creating new code file SALARY.PCF
Library code file for SALARY.pCF
= STDLZB
Please specify files to be linked into
SALARY, one per line, ending in a blank line
File 1
= SALARY
File 2 =
Loading Drogram and library dictionaries
Processing SALARY
Linking in global func/proc PROGRAM
Transferring temporary file to new code file
SALARY completed
The first thing that the command file does before linking your file is t erase any file SALARY,.PCF that already exists.
(This is because PLINK asks different questions depending on whether or not the specified program already exists, and we want to make questions.) Now it invokes PLINK.
sure that PLINK asks a particular set of
For more
Linker." information on linking a file, see Section 4.4, "The ALphaPascal
That section also discusses the meaning above, and talks about the
concept of a "library."
of the display you see
2.3.3
Running a Pascal Program
To run the program you have compiled, use the Pascal run—time package,
At AMOS command level, enter:
NUN.
PRUN SALARY.PCF
followed by information on a
RETURN.
At last your program is running!
(For full executing
Pascal programs, refer to
Section
4.5,
"The
(Changed 30 ApriL 1981)
GETTING STARTED
Page 2-9
ALphaPascal Runtime Package)
As you run SALARLPAS, you see:
AlphaPascaL V2D
What is your gross salary?
Lets assume that you want to enter 250 as your gross saLary and 175 as your takehome,
Below is a sample run of your program:
AiphaPascal V20
What is your gross salary? 250
What is your takehome salary? 175 tED
They keep 30 percent of your salary!
ALPHA PASCAL USER'S MANUAL
PART I
THE ALPHA PAScAL SYSTEM
The next two chapters introduce you to the Alpha!ascal programming system.
Chapter 3 is aimed at the experienced Pascal programmer; it discusses the differences between this Implementation of Pascal and previous versions of
AlphaPascal.
and the
It also discusses the major differences standard
Pascal as described
Manual and Report.
The last section of converting programs current AiphaPascal standards.
this
Pascal in Jensen and Wirth's Pascal User
Chapter
3 between gives some flints for written in earlier versions of AtphaPascal over to the
Chapter 4 gives full, operating instructions for the various components of the
AlphaPascal system; the compiler, the linker, and the run—time package.
Chapter 4 tells you everything you need to know about the actual processes of creating, compiling,
Chapter 4 also discusses file requirements and memory
AlphaPascal system.
linking, and running an
AlphaPascal limitations program.
of the
CHAPTER 3
COMPATIBILITY AND CONVERSION
This chapter is aimed wants to know how this primariLy at the experienced Pascal programmer who impLementation of Pascal
differs
from previous versions of ALphaPascai and from the standard Pascal described by Jensen and
Wirth in the Pascal User Manual and Report
We have also included a section that provides hints on converting Pascal programs written under earlier versions of AlphaPascal to the format used by the current AlphaPascal.
If you have never before programmed in Pascal, you skip
will
probably want to this chapter and go directly to Part II, "Summary of AiphaPascal," for information on the Alpha Micro Pascal, or to the next chapter, "Operating
Instructions and Characteristics," for information on using the AlphaPascal compi Icr and linker,
3,1
PREVIOUS VERSIONS OF ALPHA PASCAL
Previous versions of AlphaPascal were based on the UCSD
Pascal programming system,
Version
1.4.
In order to provide a Pascal that is more fully integrated with the Alpha Micro operating system and
file
system, we now offer this new version of AlphaPascal that was expressly developed for the
Alpha Micro computer.
To make life easier for programmers who have written programs using previous versions of AlphaPascal, we have tried to keep many of the same features and functions, while adding a number of new extensions and abilities.
Most of the changes between this version and earlier versions are added features that do not require that you rewrite your earlier programs.
Several of the most important difference are:
The operating instructions for AlphaPascal have changed.
An important difference is that you will use the Alpha Micro screenoriented text editor, VUE, to create your programs.
You must also use the linker,
COMPATIBILITY AND CONVERSION
Page 3—2
—
PLINK, to link any compiled program, whether or not it consists of than one
See
Chapter
4, more file.
"Operating
Instructions and
Characteristics," for complete instructions.
Expression handling has been considerably enhanced:
1.
You may now include the assignment operator in an
For example: expression.
2.
5 +
X
:
7
The expression above is equivalent to 5 +
(X
:
7), and means
"Let X assume the value of 7, and then be added to 5."
Wherever an expression is legal, you may include an
IF—THEN expression of the form:
IF condition THEN expression ELSE expression
For example:
Year
:
(IF
Feb =
Leap
THEN 29 ELSE 28)+337;
If Feb equals the value
Leap, then Year assumes the value
29+337; otherwise it assumes the value 28+337.
3.
Wherever an expression is legal, you may include a
CASE expression of the form:
CASE value OF valuel
: expression; value2
: expression;
ELSE expression
For example:
WRITE(CA$E Errorcode OF
'Illegal iiiut';
2
:
3
:
'Number too large';
'Number too small';
ELSE 'undefined error');
—
AlphaPascal.
now operators are: recognizes modifying assignment operators.
—=
1=
Adding assignment operator
Subtracting assignment operator
Multiplying assignment operator
Dividing assignment operator
These
COMPATIBILITY AND CONVERSION
S
Page
—3
These operators teLl the compiler to modify (instead of replace) the value of the variable on the left of the assignment operator with the value of the expression on the right of the operator.
For example, in the case of the adding assignment operator:
X +=
1 tells the compiler to let
X assume the value of X+1.
information on these
For more operators, see
Section
8.1.2.1, "Modifying
Assignment OperQtors."
—
Operator precedence has beenchaAqed to make it more compatible with operator precedence in other
Language processors on the Alpha Micro system.
The relational operators have ,been made of higher precedence than the Bootean operators.
(See Section 8.1.1, "Operator Precedence," for more Information.)
—
AlphaPascal allows you to label BEGIN—END blocks by following the BEGIN and END keywords:with a colon followed by an indentifler.
These labels allow you to tell the compiler which BEGINs and ENDs should match.
If the structure of your program is such that they do not match, the compiler wilt til you so.
For example:
BEGIN
:
Blocki
BEGIN
:
Btock2
END
:
Block2
END
:
BLocki
The compiler checks these Labels to make sure that the designated pairs of
BEGIN—END keywords are indeed property matched.
For exampLe, the following program would cause an error because the BEGIN—END blocks are not property nested:.
BEGIN Blocki
BEGIN
:
Block2
END
:
Blockl
END :Block2
(Changed 30 April 181)
COMPATIBILITY AND CONVERSION
Page 3—4
—
Two new keywords have been added to AlphaPascal.
These words may no longer be used as identifiers, your programs, you see an error
PROCEPURE, or FUNCTION expected —— programs.
EXTERNAL and
MODULE.
If they do appear in message
(e.g.,,
"(TRYSCAN]
VAR, scanning") when you compile the
EXTERNAL allows access variables, you to access variables, procedures, and an external library, and aLlows a file in a multiple—file
Program procedures, and functions in functions In to another file.
See
Section 6.7, "External Declarations," for more information.
The MODULE keyword designates a file that does not contain the main program portion of the program.
Modules may contain declaration and definition statements, but may not contain the final
BEGIN—END block.
(That is,
BEGIN—END blocks may only appear in function or procedure definitions if they appear in modules.)
See Section
6.1, "Program
Declarations," for more information.
—
—
The
SEGMENT keyword and seqment procedures are no Longer supported.
(See the discussions of EXTERNAL and MODULE, above.) Remove the
SEGMENT keyword from your programs.
Floating point numbers are now three words in length (i.e., 12 digits).
(They used to be two words, and could only represent six digits.)
—
You may call assembly language programs.
For information on writing subroutines from within your Pascal assembly language subroutines, see Chapter 15, "Assembly Language Subroutines."
—
Opening, closing, and specifying files have changed.
You may now access AMOS files, and make full use of the Alpha
Micro fit.
system.
Refer to Chapter 10,
"input/Output
Functions and Procedures," for more information on the procedures and functions that allow you to search for, open, and read and write sequential and random files. (NOTE: Those of you who have done assembly language programming using monitor calls on the AMOS system will recognize some of the new procedure names such as FSPEC, OPEN, OPENI, OPENO, and OPENR.)
—
AlphaPascal supports an external procedure
Library.
This Library contains a series of procedures and functions available to your programs.
You may write your own external libraries that make use of the library provided.
See Section
16.1,
"STDLIB," for a list of procedures and functions in the library.
If you wish to access these routines in your programs, your programs may not use these names in global identifier definitions, since such definitions will override the standard library definitions.
if you wish to access these procedures and functions, simply invoke them in your program.
If they are not defined within that program,
Alphapascal assumes that they are in the external library.
.
(Changed
30 April 1981)
COMPATIBILITY AND CONVERSION
Page 3—5
Several, procedures and identifiers used by previous
AlphaPascal are not supporte4 by the current version: versions of
BLOCKREAD
BLOCKWRITE
UNITREAD
UNITWRITE
UNITWAIT
UNITBUY
UNILEAR
GOTOXY
HALT
IORESULT
INTERACTIVE tiles
(Refer to Section 11.2.2, "CR1," for information on cursor positioning.)
—
PROGRAM
(the main program) may not be catted recursively.
—
You should be aware of these changes to the standard procedures:
1.
RESET and REWRITE accept only one argument: a variable of type
FILE.
You rnèy not specify a filename after that argument.
2.
3.
The file type INTERACTIVE is no longer supported or needed; replace
It with the standard file type TEXT.
In earlier versions of
AlphaPascat, CLOSE argument tn addition to a varlabtt of type took an option as an
VIE; it now accepts only a single argument—— a variabtie of type VILE.
4.
When you use the EXIT statement to exit a program, you must supply the PROGRAM keyword as the argument, not the program—name.
(That is, EXIT(PROGRAMY is valid, but EXIT(NewProgram) is not.)
You may, however, exit a procedure br function by giving the name of that procedure or function (e.g., EXIT(EvalError)).
5.
WRITE and WRITELN do not accept a Boaiean variable as an argument.
That is, If NewElte is a Boolean variable which evaluates to TRUE:
WRITELN(NewFl Ic); does not print TRUE, but instead generates an error.
COMPATIBILITY AND CONVERSION
Page 3—6
3.2
STANDARD PASCAL
The standard.
Pascal is described by Jensen and Wirth, in the Pascat
Manual and Report (Second
Edition).
AlphaPascal differs from this
User's standard in several ways (also, note the extensions discussed In Section 3.1, above):
The program heading file identifiers are scanned but ignored.
That Is, if you have any information in the program heading after the program name, that information is ignored.
equivalent to "PROGRAM
(For example, "PROGRAM MailBox;" is
Mall$ox(INPUT,ouypuT);".)
This
Is because
Alphapascal uses its own form of file handling that Is the AMOS file structure.
(Note, however, that the remainder of the heading after the program name is consistertt with scanned, and that therefore the program heading must be syntactically
If
will
correct.
For example:
"PROGRAM
NewAccount (;" generate an error because of the open parenthesis.) you want to use any files other than the predeclared file INPUT and
OUTPUT, you must use VAR statements to declare them.
—
Operator precedence has been changed to make it more compatible with other language processors on the
Alpha Micro system.
If It ts important that your program be able to run under another Pascal that uses standard
Pascal's rules of operator precedence, you will have to use parentheses In your expressions to override AlphaPascal's operator precedence.
rules of
This will only become necessary if your expressions use relational operators to compare Boolean expressions.
For example, if A, B, C, and
D are Boolean variables, standard Pascal evaluates: IF A =
B
AND C
D
THEN.., as:
IF (A =
(B
AND C)) =
D
THEN
..., white
AlphaPascat evaluates it in this way: IF (A =
B)
AND (C = D)
THEN...
(See Section
8.1.1,
"Operators," precedence.) for information on operator
—
Two new keywords have been added to the list of reserved words:
EXTERNAL and MODULE.
In addition, several identifiers have been added to the standard identifier list.
(For a list of AlphaPascal standard identifiers, see Section 5.4.2, "Standard
Identifiers.")
—
Also, several standard identifiers used by standard Pascal are NOT used by Alphapascal (DISPOSE, PACK, and UNPACK) since AlphaPascal does not use these procedures.
AlphaPascal uses MARK and RELEASE to reclaim memory alLocated by NEW, and automatically unpacks packed data structures for you when necessary.
(See Section 11,1.4, "NEW," for information on allocating dynamic variables.)
Standard
Pascal supports the data type CHAR
(single character).
AlphaPascal atso supports a non—standard type, STRING, which contains a length fieLd as well as a field of characters.
(See Section 7.2.3,
"STRING," for a description of this data type.)
.
COMPATIBILITY AND CONVERSION
Page 3—1
33 MAKING PROGRAMS COMPATIBLE thTH THE NEW ALPHA PASCAL
In general, programs written in previous versions of AlphaPascal or standard
Pascal wilt require very little modification before being runnable under the current AlphaPascal.
For example, the sample progrèm given in
Chapter
2 runs correctly in any of these versions ot Pascal.
The largest number of changes will probably involve fuWttions and proeedures that read and write disk files, since the new AlphaPascal is fully Integrated into the AMOS file structure.
If your programs were written under previous versions of UCSD/AlphaPascat, you will need to transfer your programs toAMOS files before you begin to perform any necessary conversions.
To do so, use the UCSD/AlphaPascal programming system (which was provided only in earlier releases of
AtphaPascal):
1.
At
AMOS command level, enter the
UCSD/AlphaPascal programming system by typing PASCAL followed by,a RETURN:.
PASCAL €E
When you see the initial prompt:
Command:E(dit,R(un,F(i le,C(ompl le,X)ecute,D(ebug,I(nit,H)alt
Type an F.
2.
You are now communicating with the Filer.
You see this prompt:
Fl ler:G(et,S(ave,W(hat,N(ew,L(dir,R(em,C(hng,T(rans,D(ate,Q(uit
To see what Is in your library, type L.
Now yâu see the question:
What volume?
Enter a colon followed by a RETURN.
Now you see a list that might took something like this:
5CR:
ROMAN.TEXT
4
28—Jun—80
POSTFIX.TExT
4
28—Jun—80
2 files, 8 blocks used, 26 unused
This is a list of the files in your library.
3.
You see the Filer prompt again.
To write one of the programs out to an AMOS file, enter T.
a.
The Transfer function asks you:
Transfer what file?
enter one of the files listed in the directory.
For example:
COMPATIBjLjT AND CONVERSION
Page 3—8
Transfer what file? ROMAN.TExT
b.
Now Transfer asks:
To what file?
Enter "REMOTE:' and type a RETURN:
To what file? REMOTE: fEED c.
Now Transfer asks:
Using what AMOS file?
Enter a valid AMOS file specification.
For example:
DSK1 :CONVRT..PAS
IMPORTANT NOTE: You must make sure do that this file does not already exist; if it does, the UCSD/AlphaPascal system wilt not the transfer, and will make the accessed drive inaccessible
to you (that Is, it wilt declare that drive "off tine') until
you exit or re—enter Pascal.
d.
Now Transfer asks:
CONVRT..PAS mode: T(ext, t(mage:
Enter an upper case T followed by a RETURN.
e.
Now transfer begins to copy
ROMAN.TEXT
into the AMOS file
DSK1:C0NVRT.PA$.
When Transfer is done, you see:
SCR:ROMAN.TEXT transferred to REMOTE:
You may now use the text editor, VUE, to modify the AMOS file contains your program.
may ask for additional AMOS
NOTE: If your file is too large, Transfer file specifications.
When you that are
finally
finished, you
will
need to append all such files into a single file, using the AMOS APPEND command.
Here is list of things to check when converting your old programs to current
AlphaPascal format:
1.
2.
Make sure that you do not use the reserved words EXTERNAL or MODULE
as identifiers.
Check the list of standard Identifiers in Section 5,4.2,
"Standard
identifiers,
to make sure that you do not redefine any identifiers that designate functions or procedures you need by including them in global declarations.
COMPATIBILITY AND CONVERSION
Page 3—9
3.
Remove any information concerning input or output files from your program heading.
4.
The
INTERACTIVE file type is no longer supported.
Change any occurrences of the INTERACTIVE file type in your programs to
TEXT.
It might be easiest to just redefine INTERACTIVE at the fronf of your programs via a type statement:
TYPE
INTERACTIVE = TEXT;
S.
Previous versions of AlphaPascal expected a UCSD file specification for the argument of the compiler include option, SI.
Now the
SI option request accepts an
AMOS file specification.
The default extension is
INC.
If you have used the $1 compiler option, you wilt have to change your file specifications to valid AMOS file specifications, and make sure that those files exist.
For more information on include files,
Option (SI)." see Section 4.3.2.2, "The Include
6.
7.
If it occurs in your programs, remove the SEGMENT keyword.
Note that the operator precedence used by AlphaPascal is different from that of standard Pascal and previous versions of AiphaPascat.
You may need to check expressions in which Boolean expressions are compared with relational operators to make sure that the expressions will be evaluated correctly.
"Operator Precedence," for more information.
See Section 8.1.1,
Besides changing your programs so that they will run under AlphaPascal, you might also want to add some of the new
AlphaPascal features listed in
Section 3.1, above.
As an example, instead of the statement:
*
TOTAL
:
TOTAL
+
SliM; you might want to say:
TOTAL +=
SUM
Or, you may want to break your programs up into modules.
(For information on modules, see Section 6.1, "Program Declarations.")
Of course, if you want your programs written in standard Pascal so that they can run with other Pascal implementations, you may want to restrict your programs to using features found only in standard Pascal.
CHAPTER 4
OPERATING INSTRUCTIONS AND CHARACTERISTICS
This chapter assumes that you are ready to start compiling and running
Pascal programs. If you are not familiar with AiphaPascat, you may want to skim through Part II, "Summary of AlphaPascal," before 4'ou attempt to start using the AlphaPascal system.
This chapter gives, you tnfGrmation that you will need to know about the programs that make up the AlphaPascat programming system.
The first few sections talk about file and memory requirements.
Operating instructions begin with Section 4.2, "Creating a
Pascal Program."
The AlphaPascal system consists of the compiler, CMPLLR; the tinker, PLINK;.
the run—time package, PRUN; and, the standard external library, STDLIB.
To create a
Pascal source program, editor, VUE.
use the system screen—oriented text
WE is an easy to use, powerful editor that allows you to see your Pascal program on the screen of your terminal, and to make changes to that program by moving the cursor around, on the screen display and entering the new or replacement characters.,
For, information pn using VUE, see the
AIphaVUE User's Manual, (DWM—OO100—15).
(Also, a brief, introduction to
VUE is given in Secti'on 2.3.1 of this. book, "Building a Pascal Program.")
After creating your, program, you will exit VUE and use the AtphaPascal compiler, CMPLLR, which compiles your souroe,,program (a file that has the
.PAS
extension) into a seri:es of intermediate flies.
Next you will use the
Alphapascal linker, PUNK, which uses the intermediate fites created by the compiler extension.
to create a fully resolved, runnabte P—code ,fite that has the .PCF
The linker also allows you to Link together separate files into one proqram, and allows you te update,one portton of an existing compiled program without re—compiling all of the modules thit make up that program.
To run your .PCF file, you wilt use the AlphaPascal run—time package, PRUN.
The external library contains a set of procedures, variables, and functions that are available to your Pascal programs.
For a list of the routines within the external library, see SectIon 16.1, "STDLIB." For information on writing and modifyinq your own procedures within this library, see
Chapter
16, "Writing and Modifying an External Library rile."
(Changed 30 April 1981)
U
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—2
4.1
FILE AND MEMORY, REQUIREMENTS
The
AlphaPascal system consists of these files:
DSKO:PRLJN.
PRG(1 ,4)
DSKO:CMPILR.pCFCT,5]
DSKO:PLINICPCF(7,5)
DSKO: STDLIB.PCF(7,5]
DSK0:DEMO.PASC7,5)
DSKO:DEMO.PCFrT,5)
DSKO:
UT. INC(7,5)
OSKO: SPOOL. INCC7,5)
DSKO:XLOCK.
INCC7,5)
05KG:
XLOCK. SYS(1 ,4]
05KG:
XMOUNT. INC(7,5]
DSKO:PC.DO(2,2)
DSKO:PCL.D0E2,2]
DSKO:PL.D0t2,2)
DSKO:PCU.DO(2,2)
DSKO: PU. 00(2,2)
The first four of these files must be on your system if you
AlphaPascat system.
PRUN.PRGC1,4) is a re—entrant are assembly to use the
Language program; you may load it into system memory.
CMPILR[7,5), PLINKC7,5), and
STDLIBCY,5) are Pascal code file programs.
(.PCF files may not be loaded system memory.)
DEMO,,PAS and DEMO.PCF
are the source and compiled versions of a samDle Pascal program that demonstrates file handling.
(This
The
.INC files are special files you will include in programs that make use of several of the subroutines we have provided with the AiphaPascal system.
(The special routines that make use of the .INC files are described in
Chapter 14, "Systems Functions and Procedures.") (See SectIon 4.3.2.2,
"The
Inctude Option (SI)," for information on Include fiLes.)
The
Last five files listed above are .00 files: these are special command files that help you to compile and Link files.
They invoke the compiler and tinker for you, and automatically answer alt of the questions asked by those programs.
Although these command files are not for use in all cases, you will probably be able to use them most of the time when you are compiling, linking, or updating a single file.
For information on how to use these files, see Section 4.6, "HeLpful Command Files."
4.1.1
File Extensions
Some of the extensions recognized by programming system are: various components of the Pascal
(Changed
30 April 1981)
.
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—3
.PAS
Pascai. source tile, created by text editor.
.PO1
.P02
.P03
Pascal intermediate files, crepted by the
&ompiler.
Not directLy executabLe.
.PCF
Pascal code file.
The executable prqgram file created by the tinker.
.PSB
.INC
Pascal assembly language subroutine.
Include files
NOTE: No
.PSB files have been inctuded with this release, aLthough many of the routines in the standard library are language programs.
If aàtuauly 'linked—in assembly you write your own assembly language subroutines, they must have the .PSB extension.
Theadvantage In using assembly Language programs in combination with your Pascal functions and procedures is that some systems functions can best be performed by an assembly language program because of speed, size, or hardware requirements.
4.1.2
File Search Pattern
Pascal uses a standard search patter-n in Looking for those files that it needs.
For .PCF and .INC files, this pattern is:
The account you are logged into
Your project Library account: [*,O]
The Pascal Library Account, PAS: ——
DSKO:17,5]
For PRUN.PRG, this pattern is:
System memory
User memory partition
System Library Account, SYS:—— DSKO:C1,4]
Your project library account: [*,O]
The account you are logged into
For .PSB files, this pattern is:
System memory
User memory partition
The account you are logged into
Your project library account: [*,O]
The PascaL Library Account, PAS: ——
DSKO:C7,S]
For example, if you are logged into DSK1:[100,3], and want to execute the program PRIME.PCF, you enter:
PRUN PRIME @E
OPERATING INSTRUCTIONS AND CHARACTERISTICS.
Page 4—6
(PRUN next looks assumes a it in looks file extension of .PCF,) Pascal first file in any of these places, you see the error message: looks for the file
PRIME.PCF
the account you are logged into
(in this case,
DSK1:C100,3)); in your project library account, DSK1:C100,0].
Finally It in the Pascal Library Account, DSKQ:C7,5].
If it doesn't find the
?Cannot OPEN PRIME.PCF
— file not found
Of course, if you give a and/or account specification) and account you complete file specification (including have specified, without going through its search pattern.
The standard, complete
AMOS
Paseat will look for the file on the device file specification consists of a device device specification, a file name, a file extension, and an account specification.
For example:
PRUN HWK1:PRIME.PCFC200,56] @D
4.1.3
Program Restrictions
AlphaPascal handles your programs via a virtual memory paging system.
This means that there is no limit to the size of your programs.
(NOTE: Only programs are paged, not data allocated by NEW.)
However, there are minor limits on the size of components of those programs:
1.
The object code version of any one procedure may not be larger than
2000 bytes.
2.
You may not have more than 255 global procedures and functions in any one program or library.
3.
Any global procedure or function cannot have more than
255 local procedures or functions.
4.
Maximum nesting of program block declarations is 15.
5.
Maximum nesting descriptions is 12.
of procedures, WITH—Dos, and RECORD type
4.1.4
Memory Requirements
Because AlphaPascal uses a virtual memory paging system, there is no Limit to the size of your programs.
However, a certain amount of memory is required to use CMPILR, PLINK, and PRUN.
Although the minimum size of your memory partition depends on the data space requirements of the Pascal program you want to use, you should have at Least 16K of memory to run a small program.
To compile and link a program, you should have at least 24K of memory.
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—5
Also, you should note that even though you may execute a program that Is larger than your memory partition, the larger that memory partition is, less paging must be done and, in the
To general, the faster your programs will run.
help even more in speeding up orogram execution and In reducing the minimum meAiory partition size, remember system memory.
of room in memory while compiling that you may load PRUN.PRGC1,4) into
Also, if the assembly language subroutines are re—entrant, you may load them into system memory.
that you write
If you should run out a program, CMPILR displays the messages:
?Insufficient memory or:
?Attempt to call ERRORTRAP while in ERRORTRAP
4.2
CREATING A PASCAL PROGRAM
To create or EDIT.
a Pascal source program, use one of the system text editors, VUE
If
you are using a video display terminal, you wilt probably want to use the screen—oriented text editor WE.
Ear a full description of how to use VIJE and a list of all of its commands, see the
AIph3VUE
User's
Manual, (DWM—OO100—15).
Also, Section 2.3.1, "Building a Pascal Program,r of this book contains a brief introduction to VUE.
4.3
THE ALPHA PASCAL COMPILER
The compiler reads the source program that you have created, and compiles it into three Intermediate files that have the same name as the source program file and the extensions .PO1, .P02, and .PO3.
These files are used by the linker to create the final, executable program file, which has a
.PCF
extension.
(If .PO1, .P02, and .PO3 files already exist with the same name as the program, CMPILR deletes them before compiling the new source program.)
To use the compiler, at AMOS command level enter:
PRUN CMPILRtEJ
The compiler now asks you for the name of the source file:
AlphaPascal V2.0
Source file name?
Enter the name of the file that contains tie program or module you want to compile followed by a RETURN.
(CMPILR assumes the
.PAS
extension.) source file may
This be in any account, but the .PO1, .PO2, and .PO3 files for the program will be generated in the device and account you are logged into.
(Changed 30 April 1981)
OPERATING INSTRUCTIONS AND CHARACTERISTICS
•'
Page
4—6
4.3.1
The Diagnostic Display
After you have given CMPILR the name of the source file you want to compile, it asks:
Diagnostic file name (<return> for terminal)?
The diagnostic file contains information about the, program compilation.
You wilt usually want. to see this information proceeds, and on the screen as the compilation therefore will enter a RETURN.
If you want this information sent to a file so that you can have a permanent record of the compilation, enter a valid AMOS file specification.
For, exampte:
Diagnostic file name (<return> for terminal)? DIAG
The default extension is .LST.
The diagnostic display might took something
Like this, depending on the program you are compilinq:
AlphaPascat Compiler Version, 2.0
<
0>
NEWCHECI( C 4>————
PROGRAM
C
10>
16 lines
7.07 seconds, 152.83 lines/minute
No compilation errors.
diagnostic display above shows the line nunbers at which the procedures
The the orogram begin (line #6 for the Drocedure NEWCHECK; line #10 for the main program). 'Each dash indicates the compilation of one program line.
The last three lines tell you a) how many lines were in the program; b) how quickly the compilation was done; add'c) how many errors occurred.
If an error occurs, you see it reported at, the appropriate place In the compilation.
For example, suppose we had left off a statement separator
(the semicolon) at the end of the firSt line of the program.
The diagnostic display would look like this:
AlphaPascal Compiler Version 2.0
<
PROGRAM MYPROG
0>—
VAR
Target
:
REAL;
?Line 1: CINISOP] ';'
<
1> or
'(' expected
NEWCHECI( <
6>————
PROGRAM
<
10>
16 lines
6.97 seconds, 155.02 lines/minutes
?Total of 1 compilation errors.
—— inserting
';
NOTE:
If you tell CMPILR to send the diagnostic display to the terminal screen instead of a file, CMPILR pauses when an error occurs, and gives you a chance either to continue or quit.
For example:
(Changed 30 April 1981)
.
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—?
AtphaPascal Compiler Version 2.0
< 0>—
PROGRAM MYPROG
Target
REAL;
?Line 1: CINISOP) ';
Hit RETURN to continue or
(' expected—— inserting ';'
At this point you may continue the compilation by typing a RETURN, or you may stop the compilation by typing a Control—C (in which case you see the message:
?Compilation
aborted).
If an error occurs, CMPILR does not generate the .PO1, .PO2, and .PO3 intermediate files; this is to prevent you from linking a program that contains a comDile—time error.
4.3.2
Compiler Options
The AlphaPascal compiler has a nunber of options available to you.
You may select one or more of these options at compile—time by including the appropriate option codes in your program.
You tell the compiler that you want to make an option request by
Including the symbol
$ at the front of a program comment followed by the specific option code you want to use.
The compiler acts upon the option requests as
It reaches them in the program.
Option codes may be in upper or lower case.
No space may separate the left comment delimiter and the option code.
For example, ($6—) is valid, but
'C $6—) is not.
4.3.2.1
The GOTO Options ($G+ and $6—) —
The
$G+ code tells the compiler to allow use of the GOTO statement: the
$6— code telLs the compiler to qenerate an error message if it encounters a GOTO statement.
You may use these options to turn GOTO recognition on and off within your program.
(The compiler uses the $6— option as the default; that is, it does not recognize
GOTO statements unless you use the $G+ option in your program.)
4.3.2.2
The
Include
Option
(SI) —
The
SI code tells the compiler to include the contents of the specified file in your program.
Supply a valid
AMOS file specification.
For example:
(SI MACRO.INC)
The default extension is
.INC.
The SI option code tells the compiler to physically Insert the contents of the specified file into the file being compiled. The Insertion takes place at the point of the option request.
You may not include any other option codes after the file specification.
The
(Changed 30 April 1981)
OPERATING INSTRUCTIONS AND
CHARACTERISTICS
Page 4—8 purpose of the SI option is to save used declarations or lines of code.
you from having to duplicate frequently
The
Include file pan contain any valid program elements, as long as those elements can Legally be inserted at the olace in the program where the incLude file option occurs.
(For example, you will not use the SI option request in a program's variable declaration section to include a contains a program header.) file that
NOTE:
You cannot nest tnâlude file requests.
That is, the include file may not itself contain an include file reqdest.
4.3.2.3
The List Options (SL, SL+ and SI.,—)
—
The
SI option request tells the compiler to send a listing to an AMOS file. (You do not see a orogram listing if you do not use the
SI.
option.)
Supply a valid
AMOS file specification.
For example:
<SI DSK1 : DIA6t33,2]}
The listing will now be written to the specified file.
The default file extension is .1ST.
If you do not give a file specification when you use the
SI request, CMPILR creates. a listing file bearing the name of your source file and a .LST extension in the account you are Logged into.
Of course, you may not create a listing file outside of the project of the account you are logged into.
For examDte, if you are logged into
DSKO:t100,2] and try to create the listing file DSKO:LIST.LSTC200,2J, the
AMOS system wilt respond with a "protection vioLation" error and abort the compilation because you tried to create the file in an account outside of the 100 oroject area.
You may use the codes SI— and SL÷ to turn program listing off and back on again.
For example, suppose you have a long program that contains a large section of comment that you don't want In your Listing tile.
At the front of your source program you might say:
<SI MYPROG)
Directly in front of the section you do not want in your listinq, you would place:
(SI—)
At the point where you want the listing turned back on again, place:
C$I+}
The compiler tells you in the diagnostic display that
It is writing a listing file.
For example:
(Changed
30 April 1981)
.
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—9
AlphaPascal. CompiLer VersIon 2.0
<
0>
List to LIST
ERRCHECK C
9>————
PROGRAM
<
13>
20 lines
12.36 seconds, 96.90 tines/minutes
No compilation errors.
If you want the listing to appear on your terminal screen, use th device specification TTY:.
For example:
C$L TTY:)
(NOTE: This display will be interminaled with that of the diagnostic display unless you send the diagnostic display to a file—— see SectIon 4.1.1, "The
Diagnostic Display.')
No other option requests option.
may appear after the $L
The listing consists of a display of your program with additional information to the left of the program. If your program contains errors, the
Listing file contains the appropriate error messages at the places in the program where the errors occurred.
The listing takes a form that looks something like this, depending on the program you are compiling: o line# proc lv il dsp ic/Ic
1—— Dl
0
1 1
2 —
0
1
0
1
3
Dl
0
1
6—— Dl
0
1
5—— Dl
0
1
6— Dl
0
1 1
1
1
1
1
7 ——
D 2
0
2
4
'C$LDIAG}
PROGRAM Validate { Validate nijueric entry; make sure that it is between 1 and lQO.1;
VAR
Target:REAL;
FUNCTION ErrCheck(Local
:
REAL)
:
BOOLEAN;
8 ——
D
2
0
2
9 —
0
2
0 2
10——
C 2
1
2
7
7
C Function checks entry. If 100<nuiiber<1,
ErrCheck reports error by returning a TRUE.
3-
11 ——
C 2
1
2
0
0
BEGIN C Begin function ErrCheck 3-
ErrCheck :=
Local
<
I OR Local >
100
12
——
C
2
0
2
12
END C End function ErrCheck 1;
13—— C2
0
2
40
14— Cl
1
1
0
BEGiNCMainProqram>
WRITE('Enter a number between 1 and 100:
);
15 ——
C
1 1
1
16
—
C
1
1
1
45
2
17 ——
C
1 1
1
63
READLN(Target);
IF ERRCHECK(Target)
18
——
C
1
2
1
69
THEN WRITELN('Invalid entry: try again.')
19 ——
C
1
3
1
112
ELSE WRITELN('Very good. Correct entry.')
——
C
1
0
1 compilation errors.
157 END 'C Main Program 3-.
On the right you see a listing of the program.
The left contains additional information about the program:
Line# —
This is the nunber of the program line on the right—hand side of the display. The rest of the information on this line refers to this program line.
(Changed 30 April 1981)
___________
OPERATING tNSTRUCTIONS AND CHARACTERIST!CS.
Page 4—10
Proc
You see the name of each locally
CMPILR comes to it, declared procedure as
Cor D
Pascal tells you if data (0) or code (C) is being generated for the program line, lv and
FIT
Internal information used by the compiler, is/Ic —
Indentation level,
Tells you what nesting current program line is at, level the
Internal code location counter, many total bytes have been allocated at this ooint in the program compilation for the object code of the current orocedure or function,
The ic/Ic number can come in handy later when you debug programs.
This number tells you how
If you interrupt program execution and hacktrace that program, the backtrace gives you the 'IPC' number—" the Interpreter
Program Counter," The
IPC is the number designated by ic/Ic in the program listing, you can thus compare your backtrace with your program listing, and see exactly where the problem occurs,
Also, if a run—time error occurs, the error
IPC in the procedure at which the error
?Vaiue
range error in PROGRAM at IPC =
64
(For information on backtracing,
"Interrupting a Program,) see message gives the occurred
(e,g,, within FILL,PAS),
Section 4,5,2,
4,3,2,4
The page in point the listing by telling the in the program listing, effect,
Page Option
($P)
The $P option allows you to start a new compiler to insert a form—feed at that
($P is ignored if the $L option is not in
4,3,2,5
The Quiet flptions
($Q+ and $0")
$Q+ designates the quiet—compile ootio
This option request tells the compiler to give you a brief diagnostic disp lay, leaving off procedure names and line numbers,
To turn full—display m ode back on (the default condition), use the $Q— option code,
4,3,2,6
The $R— option tells the compi Icr to turn off range checking; that is, the compiler does not output additiona sub range slightly errors,
I code to perform checking on array subscripts and assignments to type variables,
Programs compiled with range checking off run faster; however, since the compiler is not checking for range if an
•invalid index or assignment is made by your proqram, the run—time
The Range Check OQtions (SR— and SR4) package will not stop the program when that error occurs,
You
(Changed 30 April 1981)
,
OPERATING INSTRUCTIONS AND
CHARACTERISTICS
Page
4—11 should not turn off range checking until your program has been tested and you are absolutely sure that your program runs without error.
To turn range checking back on (the default condition), use the $R+ option.
4.4
THE ALPHA PASCAL LINKER
The tinker, PLINK, reads the
.PO1,
.P02, and .P03 files created by the compiler and resolves the files into a single executable program.
You may use PLINK to link multiple files together into one program.
However, even if your complete program consists of only one file, you must use
PLINK on that file to generate an executable program file.
The final file created by
PLINK has the .PCF (Pascal Code File) extension.
Although the use of PLINK may at first look complicated, once you begin to use It, you will find that its questions are rather self—explanatory.
The paragraphs below discuss the different ways in which you can use PLINK.
The last few paragraphs of this section (Sections 4.4.4 and 4.4.5) dIscuss the PLINK options.
To use PLINK, at AMOS commmand level enter:
PRUN PLINK @iD
Now
PLINK asks:
Code file:
Enter the specification you want given to your final
.PCF
file.
This specification may be that of an existing file, or it may designate a new file.
It may be the same as or different than the specification of one of the files you are going to link.
Make èure that you supply a valid AMOS file specification that cpntains a filename of no more than six characters
(for example, DSK4:VALIDC1IO,4D.
For the purposes of our discussions, let's say that you enter VALID
*
Code file: VALID@!fl
(PLINK will automatically assign the file a .PCF extension.) If you do not include a device and account specification, PLINK assumes that you want to
Link a file that is in the device and account you are logged into.
At this point
PLINK asks you different questions, depending on whether or not the specified .PCF file already exists.
In the next sections we will step through the three situations which can occur: 1) you are creating a new file; 2) you are replacing an existing .PCF file;
3) you are updating a single module in the .PCF file.
For now, let's assume that PLINK has asked its next few questions, and knows what files to link together and what external library to use.
You see:
Loading program and library dictionaries
OPERATING INSTAUCTIONS AND CHARACTERISTICS
Page 4—12
This file file.
tells
that you that PLINK is getting ready you are linking, PLINK. tells
For example: to process your file.
For each you when it begins working on that
Processing NEWNOD
Next
PLINK
tells
you being linked into your .PCF file.
the external library.)
what globally declared f%,nctions
For example: and procedures are
(These routines are in your program and
Linking 1v4 global func/proc
ERRCHECI(
Linking in global func/proc
PROGRAM
At
last,
.PCF file:
PLINK is finished, and begins to copy the resolved code into the
Transferring temporary file to new code fi I.e
PLINK's final message tells
you that it is finished:
VALID completed
Now, let's get back to the questions
files to link together.
PLINK asks when It is determining which that PLINK converts all of your input to upper case.
4.4.1
Linking a New .PCF File
If you use PLINK to create
exist,
replace or update an existing
it
that
PLINK knows that a .PCF file, and that fiLe does not already you are linking a new program, and not trying to program.
you want to create VALID.PCF.
For example, suppose you have
It tells you:
told
Creating new code file VALID.PCF
Now it asks which external library you want to use for the new program:
Library code file for VALID.PCF
=
Enter the file every case, this external
library
specification
will
be contains
You must specify linking a
"root"
Library—— own—— such as SIDLIB itself).
the of the library you want to use.
standard
library
file,
STDLIB.PCF.
The routines used by your program and the compiler.
a library (except in
the very
rire
case where
In almost you are
that is, a library that has no library of its
For information on the external library, see
Chapter 16, "Writing and Modifying which files you want to link an External Library File." Now PLINK asks together:
.
.
A
OPERATING INSTRUCTIONS
AND CHARACTERISTICS
Page 4—13
Please specify files to be Linked into VALID, one per tine, ending in a blank tine
File 1
=
Enter the specification asks for another file: of the first file; then type a RETURN.
Now PLINK
File 2
Remember that a single .PCF file may be made up compiled modules.
If you are linking only of several separately one file, enter a RETURN here; otherwise enter the file specification linking be entered in any special order, but of the next module.
If you are together more than one file, the file specifications do not have to at least one of these files must be a main program file (rather than a module), or you see the message: ?Attempt
to create new code file without main program block.
module files, see
(For information
Section 6.1, "Program Declarations.") Remember that on you are entering AMOS file specifications, and not the internal names of your programs or modules; each specification must contain a six—character or less file name that designates an AMOS disk file.
NOTE: Although you will usually be linking together compiled Pascal files, you may also want to use .PSB (Pascal assembly Language subroutine) files.
To tell Alphapascal that a file is an assembly language subroutine rather than a Pascal program file, you will specify the .PSB
extension.
example:
For
File 1
= MODUL1
@!D
FiLe
2 =
MAINPRtTh
File 2 =
INPUT.PSB
File 3
File 4
ANYCN.PSB/LINKEff
The example above shows us linking together a main Drogram file, MAINPR, a module file,
MODUL1, an assembly language subroutine file reference,
INPUT.PSB, and an assembly language subroutine,
ANYCN.PSB.
For a discussion of how these .PSB files are linked in, see Section 4.4.4, "Linking Assembly
Language Subroutines
(the /LINK Option)."
For information on assembly language subroutines, see Chapter 15, "Assembly Language Subroutines."
4.4.2
Replacing a .PCF File
If the VALID.PCF file that we specified as "code file" already exists, PLINK knows that we want to either update or replace the file. Therefore, after it asks for the code file, PLINK asks:
Do you wish to 1) replace or 2) update VALID.PCF?
To replace the file, enter a 1.
PLINK now says:
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—14
Creating new code file VALID.PCF
It asks which external library to use:
Library code file for VALID.PCF =
Once again, you wilt probably want to answer "STDLIB." Now PLINK asks for the names of the files you want to link together:
Please spqify files to be linked into VALID, one per line, ending in a blank line
File I
=
Enter the specification of the first file; then type asks for another file: a
RETURN.
Now PLINK
File 2 =
Type a RETURN if you are only linking one file; otherwise, supply the file specification of the next module.
When you have finished entering all module specifications, enter a single
RETURN.
(See Section 4.4.4 for information on linking assembly language subroutines.)
4.4.3
Updating a .PCF File
It would be extremely inconvenient to re—compile and re—link a huge
Pascal program every time you wanted to èIlange a tiny portion of it.
AlphaPascal allows you to split one program up into a number of files called
"modules," which are linked together with one main program tile.
You can change a module file, re—compile just that file, and then re—link the changed module into the main .PCF file.
-
To update a module, single module, make. your changes and then re—compile that
Now, use PLINK to re—link the modu4e into the program.
When PLINK says:
Do you wish to 1) replace or 2) update VALID.PCF?
enter a 2 followed by a RETURN.
Now It will tell you what external library was used to link that .PCF file.
For example:
The standard library code file for VALID.PCF is STDLIB.PCF
Do you wish to change this?
Answer V or N.
You will probably want to answer N, to instruct PLINK to use the same library the file was originally linked with.
If you answer
V,
PLINK asks for the new library:
New standard library
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—15
Enter the specification of the external library you want to use.
Now the
PLINK the main asks what
files
specifications of the module you want modules in the .PCF file wilt be left a new tibrary, you wilt have to re—link to link together.
or modules you have re—compiled.
Just enter the program file, since the old modules wilt be incompatible new library.
(See Section 4.5.1, information on program—library alt modules used in the program and with •the
"Library alone., compatibility.)
The rest of
NOTE; If you do change to
Version
Checking,' for more
PLINK
wilt
tell you what new procedures or functions have been linked in, and what old procedures or functions have been kept.
For example:
Keeping global func/proc ERRCHECK
Keeping global func/proc PROGRAM
Linking global func/proc NEWPROC
4.4.4
Linking Assembly Language Subroutines (the fUNK Option)
We mentioned briefly above in Section 4.4.1, "Linking a New .PCF File," that you can tink assembly language subroutine (.PSB) files into your
.PCF
by file specifying the .PSB extension when you use PLINK to link the subroutine files into the program.
(For information on such routines, see Chapter
15,
"Assembly Language Subroutines.")
What detetes actually happens is this: when you specify a .PSS file to PLINK, PLINK
then inserts a reference to that file In your final
.PCF
execute the
.PCF
it
from file, memory.
AlphaPascal searches for the specified .PSB file
(using the standard file search pattern we discussed at the file.
finishes executing the
.PSB.
When front of
chapter), and then loads that file into memory from the disk (if the file Is
not already in system or user memory); next, it executes the routine when catled by the program.
When PRUN
(You file,
it
can force PRUN to leave the .PSB file in memory by explicitly loading the file into memory via the monitor
LOAD command before using PRUN to run the program that calls the .PSB file.
the .PSB file has been placed into memory via the
LOAD command, the remains in memory until you use the DEL command to remove it.) you
this
If file
If you want the contents of the .PSB file to be physically part of your .PCF
file
(so that this search—and—load procedure does not take place), you may specify the /LINK option after the name of the .PSB file when you link that file in.
For example:
File 1 MODUL1 lEE
File
2 =
MAINPRJ
File 3 =
XPUT.PSS/LINKj
The fUNK option refers only to the single file specification on the same line as the option request.
If you are going to physically link a .PSB file into your .PCF file, the .PSB file cannot be larger than one disk block.
OPERATING INSTRUCTIONS AND CHARACTERISTICS.
Page 4—16
NOTE: UsuaUy if you modify the example, If you changed the file XPUT.PSB in not need file, modified file to
Is file re—link a part.
MODUL1.PsB, into you a module or .PSB file, you only need to
the linked .PC.F file of which It is apart..
MAINPR and our example above, you re—link
(For would
MODUL1; only XPUT.PSB.) However, if you decide to replace a .PSB file with a Pascal file of the same name or vice versa, you wilt need to re—link all modules that form the
.PCF file of which that
For example, looking at our example above again, if you decide that the tile MODUL1 would be better as an assembly language
wilt need tore—link all of the files that form the
complete .PCF fite—.MODUL1.pSB, MAINPR, and
XPUT.PS8.
4.4.5
Preventing Backtricing of .PCF Files (the /STIA$H Option)
AtphaPascal allows you to trace the functions and procedures called by a program.
program, since you can interrupt the program at a trouble spot and see what function or
This is a useful
procedure it is in.
debugging feature when you are developing a
(For more iMormation on backtraclng, see
Section 4.5.2, "Interrupting a Program.")
However, once a program has been finistied, and tested, you may not want users of that program to be able to find out the names of the program functions and procedures
/SMASH option.
(which they can ordinariiy do by interrupting the execution of the program and backtracing).
Therefore, AlphaPascal provides the linker
When you link a program using the /SMA$H option, prevented from seeing users of that program are the names pf the program!s procedures and functions when they backtrace the program; instead, the names are replaced with asterisks.
For example, instead of the backtrace dispLay:
Interrupt (?Help): 8j
In STDLIB.PCF
RDR at IPC = 33
In VALID,PCF
PROGRAM at IPC = 43
In STDLIB.PCF
PROGRAM at IPC = 423
Exit to AMOS they see:
.
OPERATING INSTRUCTIONS
AND CHARACTERISTICS
Page 4—17
Interrupt (?Help): 8 th STDLIB.PCp
RDR at 1PC33 in VALID.PCF
at
IPC
43
In STDLIB.PCF
PROGRAM at IPC
Exit to AMOS
423
Note that in the smashed version above, the name of the function in program, VALID.PCE, is blanked out with a tine of asterisks.
your own
To use the /SMASH option, pLace the option request after the name of the code file you want to smash,.
For exampLe:
Code file = VALID/SMASH tED
When
PLINK finishes linking the specified fiLes, it t.eLLs
you that the names of the functions and procedures in the code file have successfulLy been hidden from the backtrace option.
In the case of the file discussed above,
VALID.PCF, you see:
SMASHed VALID/SMASH Completed
NOTE: CMPILR and PLINK have both been linked using the /SPIASH option.
4.5
THE ALPHA PASCAL RUN—TIME PACKAGE
The AtphaPascal run—time package, PRUN, is the program that executes your program by interpreting the .PCF fiLe created by the tinker. To use PRUN, at
AMOS command level enter PRUN followed by the specification of the fiLe that contains the program you want to execute.
Then type a RETURN.
For exampte:
PRUN LSTSQRC200,1] @D
4.5.1
Library Version Checking
Because you can add routines to the external library, the situation can arise where an old program was linked with an external Library that is different from the current external library.
PRUN wiLl not execute a program that is not compatible with the library it Is being run with.
By
'compatible," we mean that a program that was Linked with a certain external library cannot be run with an older version of that Library, or with a completeLy different library.
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—18
You wiLl rarely have to worry about library version numbers; if you modify a
Library, you can run programs linked with earlier versions of that
library
without re—Linking the programs (unless you changed functions and procedures used by those programs, in which case you might have to change your programs to be compatible with the new procedures and functions).
AlphaPascal uses a system of version numbers and version stamps to keep track of program and Library versions.
(These numbers are for Internal use, only—— they are not accessibLe to your programs.) Whenever a library is created or modified, AlphaPascat writS a unique identifying number caLled the
"version number." stamp" to that Library.
It, also keeps track of the number of version stamps generated for a. Library; this number is called the
"version
Whenever you link a program,
AlphaPascal writes the version stamp and version number of the external library you are using to the .PCF file being linked.
Whenever you execute a program, PRUN: checks to make sure that the version stamp for that program matches one of the program stamps in the
current external library.
This makes sure that the current Library is not a compLetely
different
Library than the one the program was linked with.
the ltbrary Is a modified version of the
,
If
Library the program was linked with, checking to see that the version stamp in the program exists In the list of version stamps in the library makes sure that the Library is not an earlier version than the library with which the program was Linked.
If
the
library
and program are not compatible, you cannot run the program with that version of the Library; instead, you must re—link your program with the current Library.
PRUN displays the following message if the program version stamp and number of the Library are older than those of the program:
?Wrong version of xxxx for use with yyyy where xxxx is the external library, and yyyy is your .PCF file.
If you update an external library, check to see if your oLd .PAS files have to change because expected two, of the revisions.
For procedure REVERSE now expects three arguments, example, while a
if a hypothetical
previous version your programs will have to change to accommodate the changes in the procedure.
(For more information on, the external Library, see
Chapter 16, "Writing and Modifying an ExternaL Library File.")
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—19
4.5.2
Interrupting a Program
Whenever you use typing a Control—C.
PRUN, you can tell it to interrupt program execution by
PRUN stops the program being executed and displays:
Interrupt (?Jlelp):
You may enter one of four
Q
— responses: Q, R, B, or ?, followed by a RETURN:
Tells
PRUN that you want to terminate returns you to AMOS command Level.
program execution.
PRUN
R —
Tells
PRUN interruption.
to resume program execution at the point of
B
—
Tells
PRUN to print a backtrace of all the procedures and functions invoked during the program execution to this point.
These procedures and functions are listed in order, with the last—called procedure or function listed first.
The display might look something like this, depending on the program you are executing:
Interrupt (?=Help): BI!
In STDLIB.PCF
RDR at IPC
In VALID.PCF
PROGRAM
33 at IPC = 43
In STDLIB.PCF
PROGRAM
Exit to AMOS at
IPC =
423
Interrupt (?Help): QD
(For information on keeping program users from using the backtrace function to see the names of the functions and procedures in your programs, see Section 4.4.5, "Preventing
Backtracing of .PCF Files (the /SMA$H Option).")
—
Tells
PRUN that you need help.
the responses you can enter:
PRUN now displays a menu of
Interrupt (?Help): ? €!fl
Q = Quit
B =
Backtrace
R = Resume
Interrupt (?Help):
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—20
4.6
HELPFUL COMMAND FILES
Although our discussions above on the compiler and linker discussed several special uses of thost programs, in general the iaformation that you give to the programs will be fairly standard.
For example, you will rarely want to use an external library other than SIDLIB.
To make CMPILR and PLINK easier to use, we have provided a number of special command files that you can use for most cases of compilation and linking; these files automaticalLy supply much of the information needed by CMPILR and PLINK.
These command files are in the Command File Library Account, DSKO:C2,2).
(A command file is a text file that contains a series of AMOS commands and input for those command programs.
Such a file allows you to execute a string of commands and provide a stream of input by simply entering the name of that file.)
You will use these command files at AMOS command level.
To invoke one of the files, enter the name of the file followed by one or more file specifications.
For example, suppose you want to use the command file named
PC (for Pascal—compile) to compile your program file SMALL.PAS,.
At AMOS command level, enter:
PC SMALL @D
The
PC command file now invokes the Pascal compiler, and tells it that you want to compile the file SMALL.
Then it tells CMPILR that you want the diagnostic file to be displayed on the screen.
NOTE:
If an error occurs while you are using one of these command files
(for example, if your program contains an error or if AMOS cannot find the specified file), AlphaPascal stops execution of the command file.,
After you clear up the problem, you can then use the command file again.
The command files we have provided are:
DSKO:PC.DOCZ,2)
DSKO:PL.D0C2,2]
DSKO:PCL.D0t2,2]
DSKO:PCU.D0C2,2]
DSKO: PU.D012,2]
Pascal—compile
Pascal—Link
Pascal—compite and —link
Pascal—compile and —update
Pascal—update
Remember that these command files do not cGver all cases of compiling and linking files.
If after you read these descriptions you realize that the file will not do exactly what you need, you will have to run CMPILR and
PLINK yourself to perform the actions you want.
4.6.1
Compiling a Single File (PC.DO)
To use the PC file, enter PC followed by the name of the file that contains the program you want to compile.
Then type a RETURN.
For example:
PC DRWLIN E
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 4—21
CMPILR compiles and DRWLIN.p03.
the file DRWLIN.PAS into the files DRWLIN.PO1, DRWLIN.P02,
4.6.2
Linking a Single File (PL.DO) you want
P1 DRWLIN fj
PLINK now links the files DRWLIN.PO1, DRWLIN.P02, and into DRWLIN.PCF.
already been
Before you try to link a
compiled; that is, that the .PO1, .P02, and .P03
P1 assumes that you want standard external library, SIDLIB.
file, make
DRWLIN.P03 together sure that
it
has
files exist.
to link a single file, and that you want to
use the
4.6.3
Compiling and Linking a Single File (PCL.DO)
To use the PCI file, enter PCI followed by the compile and link.
For example: name of the file you went to
PCI TRSRCH
The compiler compiles the file
TRSRCH..PAS
into the files TRSRCH.PO1,
TRSRCH.P02, and TRSRCH.P03.
TRSRCH.PCF.
Next, PLINK links these intermediate files into
The command file assumes that you want to link a single program file, and that you want to use the standard external library, STDLIB.
4.6.4
Updating a Single Program Module (PU.DO)
To use the PU file, enter PU followed by the name of the module you want to update, into.
followed by
For example: the name of the .PCF file you want to Link the module
Pu MODUL1 TRSRCH @23
PLINK now links the module into TRSRCH.PCF.
has already been compiled, and library TRSRCH was originally linked under.
This file assumes that
MODUL1 that you want to use whatever external
OPERATING INSTRUCTIONS AND CHARACTERISTICS
Page 422
465 Compiling and Updating a Single Program Module (PCUDO)
To use the PCU file/enter PCU followed by the name of the module you want to compile and update, followed by the name of the PCF file you want to link the module into,
For example:
PCU MODUL1 TRSRCH
CMPILR now compiles MODUL1; assumes that you want to linked under,
PLINK then links it into
TRSRCH,PCF,
PCU use the external library TRSRCH was originally
ALPHA PASCAL USER'S MANUAL
PART II
SUMMARY OF ALPHA PASCAL
The next nine chapters discuss the elements of the Pascal Language been implemented by Alpha Micro.
refer to Appendix A, "A Quick Reference to AlphaPascat." as it has
If you are interested in a quick summary,
CHAPTER 5
GENERAL INFORMATION
This chapter contains very general information about AtphaPascat program concepts such as: basic program structure, statement separation and spacing, legal identifiers, compound statements, scope of
identifiers,
etc.
For detailed Information on specific elements of a
Pascal program, see the Index and Appendix A, "Quick Reference to AlphaPascal."
5.1
BASIC
STRUCTURE
OF A PROGRAM
This section lists the major elements of a Pascal program.
We'll talk more about each element in the following paragraphs, but this will give you a general idea of what goes where.
Every Pascal program follows the general form:
Heading block.
The heading follows this form:
PROGRAM program—name;
PROGRAM;
NOTE: Standard Pascal requires that you follow the program—name with a set of names that are concerned
PROGRAM
Schedule(INPUT,OUTPUT);).
with program input and output (for example:
AlphaPascal, however, ignores these names, and you may omit them altogether.
However, make sure that the program heading is syntactically correct. (For example, "PROGRAM
C;" generates an error message because of the open parenthesis.)
NewAccount
The program block which appears under the heading consists of a dectaration section that defines the names and properties of various data objects
(such as variables and constants) and subprograms
(such as procedures and functions) that will be used In the program, and a statement section, which
GENERAL INFORMATION
Page 5—2
lists
the actions to be taken upon the declared items.
(The names of the data objects, as weLt as the names of the procedures and functions of a
Pascal program are form: called
"identifiers.')
The program block takes this
Label—declaration part
Constant—definition part
Type—declaration part
Variable—declaration part
External—declaration part
Procedure—and—function—declaration part
Statement part.
(For information on the definition and declaration sections of the program block, see
Chapter
6, "Declarations and Definitions."
For information on the statement section of the program block, see Chapters 9—13.
Any number of spaces and/or blank tines may appear between words and symbols in a Pascal program.
Because program statements may be broken up by blank lines and spaces, Pascal requires that you identify where one statement ends and another begins by separating them with a semicolon.
For example:
PROGRAM Newlest;
VAR Counter
:
REAL;
The last element of a Pascal program must be the END keyword followed by a period.
(The period indicates that the end of the program has been reached, rather than just the end of a group of Statements within the program.)
As a final word on program structure, we would like to mention that your program can consist of more than one file.
The advantage of splitting your program up Into multiple files is that when a change needs to b! made to one of the files, you only have to re—compile the one file and then re—link the
files, rather than re—compile all of the files.
If your program does consist of multiple fiLes, only one of those files will follow the main program format we discussed above; the rest wilt follow a
slightly different format.
(This is because only one main program file may be linked format:
together with other files.)
These non—program files follow this
MODULE module—name; block.
or:
MODULE; block.
This heading tells the Pascal compiler that the file is not a main program file, and that
it
is part of a multiple—file program.
The module—name identifies this non—program file, and does not necessarily have to be the
U
GENERAL INFORMATION
Page 5—3
I
same name as that assigned to the
actual file or to the main
program.
The btock takes this form:
Label—decLaration part
Constant—definition part
Type—dectaration part
Variable—declaration part
External—declaration part
Procedure—and_function..dectarat ion
Dart
As you can see, the file does not contain course, the procedure and function section.)
The a statement part.
declarations can contain a statement file ends with a period (even though it
END keyword fottowed by a period).
(Although, of cannot end with an
Below is a small sample of a module and the main program with which linked:
It is
A MODULE
MODULE;
FUNCTION MAX(Argl,Arg2
:
REAL) :
REAL;
BEGIN C MAX )
IF Argl>Arg2 THEN MAX:Argi ELSE MAX:Arq2
ENV{ End of MAX };
A
MAIN PROGRAM
PROGRAM Main;
VAR
NumI, Num2
:
REAL;
EXTERNAL FUNCTION MAX(Arql,ArgZ
:
REAL) REAL;
BEGIN { Main Program )
WRITE('Enter two numbers: ');
WRITELN;
READLN(Numl,Num2);
WRITELN('The larger number is: ',MAX(Numl,Num2))
END C
Main Program ).
5.2
COMPOUND STATEMENTS (BEGIN AND END)
The statement section of the program block starts with a BEGIN keyword and ends with an END keyword.
The elements within these two keywords may consist of one statement or many, and comprise the executable section of the program.
(Changed 30 April 1981)
GENERAL INFORMATION
Page 5-'4
Any one statement
"compound statement," may be replaced by a combination of statements called a
A compound statement is a series of statements, and starts with the
BEGIN keyword and finishes with the END keyword.
By convention, the programmer usually indents each compound statement one level within the program (see the example below) so that he or she can visually keep track of how compound statements are nested,
The individual statements within the compound statement must be separated by a semicolon,
For example:
PROGRAM Average;
C This program computes the average of a series of numbers 1
VAR
Count
:
INTEGER;
Answer, Total, Num
:
REAL;
CONST Maxval 10;
BEGIN C Average }
Total
0
FOR Count
1
TO Maxval DO
BEGIN
WRITE CEnter number, please: ) C Prompt user for number it;
READLN(Num) C Get number from user it;
Total := Total ± Num C Sum numbers it
END;
Answer := Total/Maxval C Compute average it;
WRITELN CAverage is: , Answer)
END C Average it,
In the example not keyword with a semicolon,
This is because BEGIN and END are keywords, but are above, the statement section of the program block cortains two nested BEGIN'END compound statements, require a semicolon after
it,
and
Note that the BEGIN keyword does that you do not precede the END not statements,
Therefore, there is no need to separate BEGIN from the
WRITE statement
•in fact, doing so causes an error, For the same reason, do not place a semicolon between the END keyword and the statement before it,
5,3
COMMENTS
Sometimes the function of a section of a program is not immediately obvious to the casual observer, program,
To help the reader of a program understand what that program is doing,
Pascal allows you to enter comments" in your
Comments program, are ignored by the compiler, and serve only to document the source
AlphaPascal accepts as comments any text enclosed either by a pair
of "Ct" or "(* *)" symbols,
For example:
READ(PianeRoute)
(* This variable is accessed by FLIGHT procedure *);
A comment may appear between any two symbols in a program, cover more than
(Chanqed 30 April 1981)
GENERAL INFORMATION
Page 5—5 one this line, and may allows
For example: you appear in the middle of nested, but 'C) symbols.
a statement.
may appear within the symbols (* *), to "comment out"
Comments may not be and vice versa; areas of programs that contain comments.
(* WRITELN(RecCount)
READLN;
IF Error THEN ErrorFix 'C
'C Report # of records sorted )
Error condition ); *)
5.4
LEGAL IDENTIFIERS
Identifiers are groups of characters that denote constants, procedures, functions,
tagfields.
assumes the
As one example values of program as the Identifier Scores.
an programs,
identifier,
record consider variables, fields, a and types, record variable that of a range of school test scores; it might appear In a
Identifiers in AlphaPascal case may consist of combinations of upper letters and numbers, but must begin with a letter.
as many characters as you wish, but only by Pascal in recognizing the
identifier.
the first eight characters
(That means that
STANDARDBUFFER and STANDARDBUFFOON will be recognized identifier—— STANDARD.) and lower
Identifiers may be the are used
Identifiers
by Pascal as the same
IMPORTANT NOTE: AlphaPascal "folds"
This means considering that
identifiers
Evalauote,
Evalquote,
identifier.
It
translates
identifiers.
In other lower case identifiers to upper case.
all lower case letters to
words, upper case when
AlphaPascal considers the
EVALQUOTE, and CvaIQUOTE to be the same
You may choose any combinations the following exceptions.
words") have been reserved by
listed
the identifiers") have
AlphaPascal functions, and types already defined to AlphaPascal.
standard in
identifiers
so that they functions, and procedures.
standard identifier, no
identifier.
recognizes these
identifiers
(Of which it appears.) section been and course, pre—declared by no standard identifiers as denoting procedures, keywords is
AlphaPascal.
This means that you longer represent that
The difference between
MAY redefine standard predefined Pascal types,
In other words, if you attach error message function or type previously a
of letters and numb!rs for identifiers
with
Certain words (called "keywords" or "reserved
Pascal to identify statements inherent to Pascal, and may not be used as Identifiers.
below.)
Other is
identifiers
generated; available to the procedure or function in but, which you and a new meaning to a the structures
(These keywords are
(called
associated with that identifier is
"standard procedure, no longer redefined the re—definition only applies to the program in
For this reason, you must be very careful when assigning identifiers not inadvertently redefine a standard
Identifier
whose function you may have need for later on in the program.
to procedure, type, or
GENERAL INFORMATION
Page 5—6
5.4,1
Reserved Words
Below is a list of the
Pascal reserved words.
You may not use these reserved words as identifiers.
AND
DIV
EXTERNAL iF
NIL
PROCEDURE
THEN
WHILE
ARRAY
DO
FILE
IN
NOT
PROGRAM
TO
WITH
BEGIN
DOWNTO
FOR
LABEL
OF
RECORD
TYPE
CASE
ELSE
FUNCTION
MOD
OR
REPEAT
UNTIL
CONST
END
GOTO
MODULE
PACKED
SET
VAR
5.4.2
Standard Identifiers
Below is
a list of all AlphaPascal standard identifiers.
You may redefine
these identifiers.
However, be careful not to unintentionally redefine them.
Constants:
Types:
FALSE
TRUE MAXINT
INTEGER
TEXT
Predectared files:
BOOLEAN REAL
CHAR
STRING
INPUT
OUTPUT KEYBOARD
Procedures, variables and functions.
(NOTE: Several of these procedures, variables, and functions are for internal use of the compiler and standard
library.
For a list of all functions and procedures available for your use, refer to
Appendix A, "Quick Reference to A1*haPascat," or to the Table of
Contents.)
.
•
•
GENERAL INFORMATION
NEW
OPENO
PFILE
PUT
RAD5O
RDR
RELEASE
RLN
SEEK
SINH
SQR
STRIP
TIME tiCS
WRC
ABS
ARCS INN
CHR
COS
DELETE
ERROR
EXP
FILLCHAR
GETFILE
INSERT
LCS
LOCATION
MARK
WRR
XMNT
ARCCO$
ARCTAN
CLOSE
•-COSH
EOF
ERRORINFO
EXPONENT
FILESIZE
GETLOCK$
JOBDEV
I,ENGTH
LOG
MEMAVAIL
ODD
OPENR
PUS
PVIRT
RANDOMIZE
RDS
RENAME
RND
SETFILE
SIZEOF
SQRT
SUCC
TOD
VAL
WRI
WRS
XMOUNT
ARCCOSH
ARCTANH
CONCAT
CREATE
EOLN
ERRORTRAP
EXTENSION
F$PEC
IDSEARCH
.JQBUSER
LINEMODE
LOOKUP
MOVELEFT
OPEN
ORD
POWER
PWROFTEN
RDC
READ
RESET
ROUND
SHIFT
SPL
STDERRORTRAP
TAN
TREESEARCH
WLN
WRITE
XERRORTRAP
ARCSIN
CHARMODE
COPY
CR1
ERASE
EXIT
FACTORIAL
GET
INCHARMODE
KILCMD
LN
MAINPROG
MOVER IGIIT
OPENI
PAGE
PRED
PWROFTWO
PD!
READLN
REWRITE
SCAN
SIN
SPOOL
TANH
TRUNC
WRB
WRITELN
XLOCK
Page
5—7
5.5
SCOPE OF IDENTIFIERS
Because
Pascal is a block structured language, a
Pascal program falls naturally into a nested structure.
(See Figure 5—1, below.
Each Block in the diagram represents some procedure or function within the program.)
What happens if, for example, a variable is declared in the main program, and then re—declared in a procedure catted by the main program?
Which declaration is valid?
This problem is resolved by defining the "scope' of the identifier; that is, by defining the area of a program for which the declaration of an identifier is valid.
The scope of an identifier is the program, procedure, or function in which it is defined and any enclosed btockswhich do not redefine it.
(The use of an identifier in the same block as its declaration is called a
"tocal reference; the use of an identifier declared in an outer block is called a
"non—local" reference.)
(Changed 30 April 1981)
GENERAL INFORMATION
BlockA
Main Program
BLockA
Page 58
A2
kB2
Figure 5—1
Nested Structure of Program BLocks
Lets say that a constant is defined both in the main program and
B1ockA
BlockA
itself
and the blocks enclosed in BlockA (BiockAl and BlockA2) use the definition made in BiockA,
The main program, BlockA,
BlockBl, and
BLockB2 use the constant definition made in the main program.
The foLLowing small program demonstrates identifier scoping
Counter is declared both within the main program and
The variable within the procedure
InnerB Lock:
(Changed 30 prit. 1981)
GENERAL INFORMATION
Page 5—9
PROGRAM Scope 'C Tjiis program tests identifier scoping };
VAR
Counter
: INTEGER;
T "Counter' declared for main program >
PROCEDURE Inrtere lock;
VAR
Counter
INTEGER;
T "Counter" declared for Procedure Innerelock 3
BEGIN
Counter
:
1;
FOR Counter
:
BEGIN
1 1010 DO
WRITELN('Procedure InnerBlock——
END
END tind Procedure InnerOtock
3;
Counter = ',Counter);
BEGIN C Main Program 3
Counter
:
20;
WRITELN('Main Program—— Counter = ',Counter);
InnerBlock C Invoke Procedure InnerBl.ock
3;
WRITELN('Main Program again—— Counter
END C End Main Program 3.
= ',Counter)
If our description of statement:
Identifier scoping is correct,
we would expect the
WRITELN('Majn Program again—— Counter= ',Counter) to produce the value 20, regardless of the value assumed by
Counter within the procedure InnerBlock.
That is exactly what happens.
5.6
NOTATION
AlphaPascal uses and strings.
several conventions in handling and representing numbers
5.6.1
NUMBERS
Pascal recognizes two types of numbers: integer and numbers part.
are
The integer the "whole numbers"; that is, they cannot contain a fractional
Real numbers are numbers that contain therefore contain a fractional a decimal real.
point, and which
part (even if that fractional part Is zero).
For example, these numbers are integers:
—231
7
8098
GENERAL INFORMATION
Page 5—1,0
These are real numbers:
567.8
—25.00
4.318
(For information on the REAL and INTEGER data types see Chapter 7, "Data
Types.') Pascal has two methods of displaying numbers: decimal noitatton and scientific notation.
Decimal notation allows us to represent a number with an optional sign, a whole number part, a decimal point, and an optional fractional part.
If the fractional part exists, there must be at least one digit on each side of the decimal point.
For example:
—2405.3
Scientific notation is handy for representing very small or very large numbers.
A number represented in scientific notation is shown as a value multiplied by the appropriate power of 10.
To indicate the exponent, Pascal uses the symbol "E".
For example:
—2.4053E+3 represents "negative 2.4053 times 10 to the third"; that is,
In decimal notation, the number would be —2405.3.
A positive number after the E tells you how many places to shift the decimal point to the right, in order to read the number in decimal notation; a negative number tells you how many places to shift the decimal point to the left.
For example, to represent the number:
5.678E—2 in decimal notation, shift the decimal point to the left two places: 0.0567.
Alphapascal generally uses decimal notation to display real and integer numbers.
(Of course, if the number is integer, no fractional part shown.)
However,
Is
If a number is too large or too small to represent easily in decimal notation, AlphaPascal displays it in scientific notation.
You may use either scientific or decimal notation when entering numbers to a
Pascal program, or within the program itself.
(For information on using the WRITE and WRITELN procedures to format numeric and character output, see Section 10.1.5.5, "Formatting
Output.")
5.6.2
STRINGS
A string is a group of characters.
These characters may be numbers, letters, or any comment—— 0 or (*
*)
A a string is identified to Pascal by enclosing it in single quotation marks.
For example:
GENERAL INFORMATION
Page 5—11
'This is a string.'
'Data: 123'
'The END itnear'
The characters in reserved words, etc.
"123", but a string represent themselves, rather than numeric values,
For example, the third does not represent the example contains the characters number 123.
The fourth example contains
END.
If you wish a string to contain a quotation mark, place two quotation marks
For example:
'You don''t say.'
A string may be defined in a constant definition.
For example:
CONST Message
'Error — Type CR to recover'
(We then say that Message is a string constant.)
as a string literal.
For example:
Or, a string may be used
WRITELN('Do not forget to write—enable
the disk.')
NOTE: Alphapascal includes
Data the data type SIRING as of type
STRING consists of a a standard data type.
group of characters (data of type CHAR) rather than a single character.
Chapter 7, "Data Types.'
For information on
CHAR and
STRING, see
.
CHAPTER, 6
DECLARATIONS AND DEFINITIONS
One of the important features of Pascal is that it requires that you define and name the data objects you are going to, use reference those objects.
For example, variable named 'Cost', you must 'dectare" that variable at the start of the program or procedure in which that variable appears.
Besides declaring variables, you must also declare the program name, labels, functions and procedures, and modules.
Zn addition, you must define any numeric or string constants you are going to use, as well as any data types.
and function containing the declared data objects.
if in a program before you you are going to be using a
All declarations definitions appear at the front of the main program or the procedure or
These centralized declarations and definitions greatly enhance the
legibility
and organization of your program, and aid the compiler in performing error detection.
You'll remember from Chapter 5 that the declaration and definition part of the program block takes the form:
Label declarations
Constant definitions
Type declarations
Variable declarations
External declarations
Procedure and function definitions
6.1
PROGRAM DECLARATIONS
The program declaration contain a program name.
main consists of the
PROGRAM.
This program declaration assigns the name program, and marks the start of the main program file.
A program name may be any legal identifier (see Section
5.4, "Legal program declaration statement takes the form: keyword.
It may also
Identifiers").
of the
The
PROGRAM prog ram—name;
DECLARATIONS AND DEFINITIONS
Page 6—2 or:
PR
PG RAM;
Unlike other versions of Pascal, AlphaPascal does not require or recognize any information about external input or output files after the program name in the program declaration, Neither does AlphaPascal attach any significance to the program name.
That is, the program name serves only as a type of comment, and does not actually identify the file,
End the program declaration with a semicolon to separate it from the rest of the program statements, For example:
PROGRAM BubbleSort;
An AlphaPascal program may consist of more than one file.
You can compile these
files
one program, separately; then, using PLINK, you can link them together into
Of the files that you are going to link together, only one may be a main program file,
You tell the linker which files are
not the main program
those files,
This declaration tells the linker that the
main
file
by program (that including an external program declaration at the front of
it
file is not the
is, in effect, an external file to the main program),
The declaration takes the form:
MODULE module"name;
(where module"name identifies the non"program file, and does not need to be the same as the name of the main program) or:
MODULE;
If
a file does not contain the main program, there are some restrictions on the elements that it can contain,
For information on the format of a non"program file, see Section 51, "Program Structure,'
6,2
LABEL DECLARATIONS
If
you want
to transfer control to a particular section of
a program, you must label that section with a
"statement label,"
Labels are unsigned integers from
0 to 32767, and must statement, be declared in a label declaration
The label declaration statement takes this form:
LABEL one or more numbers, separated by commas;
For example, if we want to use the labels 25 and 100 in a program, the declaration looks like:
LABEL
25,
100;
Labels appear in the program in front of the statement they designate, and end with a colon,
For example:
DECLARATIONS AND DEFINITIONS
'
Page 6—3
25: IF EOF THEN WRITELN('End of file.');
To reference a labeled statement, use the GOlD statement.
(For information on GOTO, see Section,9.4, "GOb.")
In addition to the standard labels we talked about above, AlphaPascal also recognizes another type of label which appears after the BEGIN and END keywords.
The purpose of these labels Is to enlist the compiler's help in determining whether or not you are properly nesting
BEGIN—END blocks.
If the same Label appears after two BEGIN, and. END keywords, the compiler checks to make sure that,,, the keywords do Indeed, mark the beginning and end of a if they do not, the compiler reports an error ("CSTMBID) Wronq
BEGIN—END
Identifier
—— XXX expected," where
XXX is the block label
This helps you to make sure that the structure of your program is correct.
An example may help to clarify.
Look at the following program diagram:
BEGIN
:
Labell
BEGIN
:
LabetZ
END
:
Label2
END
:
*
Labell
The example above shows a program in which the bLocks are properly nested.
By including the labels "Labell" and "Label?", we have asked the compiler to check the program structure and Sake sure that the BEGIN and END keywords are Indeed nested properly.
The program below wilt cause the compiler to report an error:
BEGIN : Blocki
BEGIN :
Block2
• END
:
END
:
0
Block?.
since the
END keyword for Blocki appears before the END keyword of Block2.
The BEGIN—END label may take the form of any Legal identifier, and must be separated from the keyword by a colon.
(Changed 30 AprIl 1981)
DECLARATIONS AND DEFINITIONS
Page 6—4
6.3
CONSTANT DEFINITIONS
Defining constants wilt be helpful whenever: you have a string or ntrerlc literal that is used frequently within a program; a literal is important to understandjng the logic of the program; or a literal may possibly be changed in future versions of the program.
(For irformat1on on constants, see
Section 8.2, "Constants.")
Th! constant definition takes the form:
CONST identifierl = ldentifler2 S nunber or string; ntsnber or string;
.
S
S identifierN
= nunber or string;
For example, Instead of repeating the expression
"Radius throughout a program, you might want to define the constant
Pi:
*
3.1415927"
CONST
P1
3.1415927
Then, wherever your say: "Radius * program used to say "Radius *
3.1415927", you can now
RI".
This keeps your program easy to read.
Also, If at a future date you have to change a literal in your program, it Is now a simpte matter since you have only to change one constant definition statement instead of every occurrence of that literal in the program.
As an example of a string literal, consider the statement:
WRITELN('You have entered an invalid ntsiber—— try again');
If you use this string more than once, you might want to replace it with a constant:
CONST Error =
'You have entered an invalid ntsnber—— try again');
Now your statements can read:
WRITELN(Error);
6.4
TYPE DECLARATIONS
The most important feature of
Pascal
Is its use and definition of the concept of "data types."
A data type is a set of data (for example, whole nunbers) that are alike in some way.
For more information on data types, see Chapter 7, "Data Types."
For now, let's just say that Pascal gives you some very powerful ways of representing different kinds of data types.
Besides the standard types that Pascal recognizes
(for example, the type
INTEGER, that represents whole nunbers), Pascal also allows you to define your own data types.
You must declare a user—defined data type at the front
(Changed
30 April 1981)
5
DECLARATIONS AND DEFINITIONS
Page 6—5 of the main program or procedure inwhich you are going to access that data type.
The type deálar.ation takes this form:
TYPE identifierl = typel; ldentifier2 = type2;
.
idectitierN = typeN;
For example, suppose you want to define a new data type simply enumerating the elements of that type: that is a simple scatar type whose elements are:
MON,
TUES, and WEDS.
You can do so by
TYPE
Days = (MON,TUES,WEDS);
On the other hand, suppose you want to declare a more complicated data type, such as a type of array:
TYPE NewArray = ARRAY t1..1O) OF INTEGER;
The declaration above declares an array named NewArray which contains 10 elements (which are to be indexed by the tiumbers 1 through 10).
The elements are of type INTEGER.
6.5
VARIABLE DECLARATIONS
Pascal requires that all variables be
"declared.'
This means that you assign a name variable.
to a variable and permanently associate a data type to that
Since you tell Pascal the data type of each variable, Pascal knows what operations can be performed on that variable, and which functions and procedures can be used on It.
Be aware that
Pascal.
does not assume an initial value (e.g., zero) for a declared variable; you must explicitLy assign a value to a variable.
If you try to assign a value that is not consistent with the data type associated with that variable, the Pascal compiLer generates an error message.
The variable declaration statement takes the form:
VAR identifier.. .,identifier
: data—type; identifier...,identlfier
: datátype;
S
identifier...,identifier
: data—type;
For example:
DECLARATIONS AND DEFINITIONS
Page 6—6
VAR
TestScores, Variance, Mean :
REAL;
StudentlD,
ClassName,
StudentName, Teacher
:
STRING;
Passed
BOOLEAN;
The variable name may be any
legal identifier.
The data types yoz can assign to a variable are discussed in Chapter 7, "Data Types."
6.6
FUNCTION AND PROCEDURE DECLARATIONS
You may often need to perform the same sort of actions on a body of data throughout your program.
piece of code every
Rather than forcing you tb place
It
IS generate "subprograms' which may be needed,
call!d
Pascat gives you two ways to upon tediously wherever duplicate one neded in a program.
These subprograms are cat led"functions" and "procedures." Such subprograms atso help you to maintain your programs since, if a change must be made, it only needs to be made once.
Although you may invoke these functions and procedures any place in the statement part of your program
(or functions and procedures), you must within the declarations of other first define the functions and procedures within the declaration part of your program before you invoke them.
(A special case exists for referencing funflions and procedures within other functions and procedures before they have been defined; see
Section 6.6.3, "Forward Declarations.")
Functions and procedures can be thought of as prpgrarns within a program.
They can declare variables, define and invoke procedures and functions of
their
own (known as "local" procedures and functions), and input and output data.
6.6.1
Functions
A function is a subprogram that performs some computation and returns a value.
(For example, the standard funçtioñ ABS takes a number and returns the absolute value of it..)
Pascal allows you to define your own functions by including function declarations at the front of the program or procedure
that will call that function.
Function declarations must appear after any variable declarations.
The function declaration takes this form:
FUNCTION function—name (format parameters)
: function—block; data—type of result; where the format parameters are identifiers that describe the variables (and
their
data types) which will be used within the function.
These variables do not have to appear in a variable declaration statement, since they are being declared within the function heading.
DECLARATIONS AND DEFINITIONS
-
Page
6—7
Fol towing the format parameters is the data function.
For example: type of the result of the
FUNCTION SufficientFunds(Request
BEGIN
:
SufficientFunds
:
Request <=
REAL)
:
BOOLEAN;
AmountAvaitable
The heading above might identify a function that returns TRUE if a checking account has enough funds to cash a spectfled check.
The function block starts with the BEGIN keyword and finishes with the
END keyword.
The statements in between perform the action on the input data when the function is executed.
The function block takes this form:
Labet declarations
Constant declarations
Type declarations
Variable declarations
Procedure/function declarations
BEGIN—END block
As you can see, the block of the function follows much the same form as the program block itself, except that a function semicoton, rather than a period.
definition ends with
At some point withtn the BEGIN—END block, a a value must be assigned to the function name ttself.
This is the way that the result of the function is returned to the program or procedure that invoked it.
To invoke a function, Include the name of the function within the program block along with the names of the variables that are going to supply that function with data.
For example, to invoke the function SufficientFunds, you might include a statement line like thts:
IF SufficientFunds (100.50)
THEN WRITELN('Good check')
ELSE WRITELN('Sorry, overdrawn');
The statement above prints 'Good Check' if SufficientFunds returns TRUE, and
'Sorry, overdrawn' if it returns FALSE.
You may supply variables, expressions, or constants as the arguments of the function.
Note that the names of the variables you pass to the function do not have to have the same names as those variables listed in the function heading.
The first variable
(or constant) mentioned in the function invocation is substituted into the function for the first variable mentioned in the function heading, the second variable (or constant) in the invocation replaces the second variable in the function heading, and so on.
(Of course, the data types of the variables must be consistent.
For example, if you supply the variable Check to the function SuffictentFunds, it must contain a number of type REAL.)
Remember that a function Invocation is always part of an expression.
example, given the function NaxNum, these are valid function invocations:
For
DECLARATIONS AND DEFINITIONS
Page 6—8
WRITELNYThe Largest number is: ,MaxNum(Number1,Number2fl; or:
IF MaxNum(VaLuel,Value2) C 0 THEN WRITELN(Numbers are
negative);
Lets
Look at an exampLe of a function and function invocationS Suppose your program frequently needs to check the range of input numbers
A simple function to make sure that a number is between
1 and 100 might
Look something Like this:
PROGRAM Validate; C Validate a numeric entry; make sure
that it
is between 1 and 1OO }
VAR
Target
:
REAL;
FUNCTION ErrCheck(LocaL
:
REAL)
:
BOOLEAN;
C Function does error checking on entry If 100 C number < 1,
ErrCheck reports error by returning a TRUE )
BEGIN C Begin function ErrCheck }
ErrCheck
:
Local C
1
OR LocaL > 100
END C End function ErrCheck J-;
BEGIN C Main Program }
WRITEYEnter a number between
1
and 100: );
READLN(Target);
IF ERRCHECK(Target)
THEN WRITELNYInvaLid entry: try again)
ELSE WRITELN(9Very good Correct entry')
END C Main Program )
Note that untiL the program begins executing the main program, where the function is actuaLLy invoked, the function is not executed, even though the function definition appears at the front of the program
662 Procedures
The major purpose of a function is to compute and return a vaLue The main purpose of a procedure is to perform a set of operations
For example, lets say that you are designing a program that plays a card gameS
At various times throughout the program you may need to simulate the of your program (which would make the program hard to read and may a deck of cards shuffling
Rather than include this same piece of code throughout maintain), you designate this piece of code as a procedure
The procedure declaration names the procedure, tells what kinds of variables it will use, and gives the statements that make up the procedure
It takes this form:
PROCEDURE procedure—name (formal parameters); procedure—block;
DECLARATIONS AND DEFINITIONS
S
Page
6—9
The formal parameters list the vafiables (and their types) with which the procedure wilt work.
'for example:
PROCEDURE PrintReport (Title
:
STRING; PageSize
:
INTEGER);
The procedure block takes this form:
Label declarations
Constant dec (.arat ions
Type declarations
Variable dectarations
Procedure/function declarations
BEGIN—END block
F
To invoke the procedure, include the name of the procedure within your program.
Unlike a function invocation, a procedure invocation Is a program statement, not an expression.
For example, say that you have a procedure named Shuffle that simulates the shuffle of a deck of cards:
BEGIN
IF Dealer =
New OR Deck =
THEN Shuffle
END;
Empty
Although a procedure may take a form very much like that of a function, it does not necessarily return a value.
Notice that it also does not have to accept any arguments.
(For information on using procedures to return several results, see Section 6.6.4.2, "Reference Parameters.')
6.6.3
Forward Declarations
What happens when a procedure or function declaration invokes a procedure or function whose declaration has not yet appeared In the program?
times when
There are for aesthetic or practical reasons (or because the two routines call each other) you must invoke a procedure or function before
Its definition appears in the, declaration part of the program.
Pascal provides a way to do this.
The forward declaration tells the Pascal compiler, "We'll define this later; don't worry that you haven't seen its declaration yet.'
The forward declaration takes the same form as the heading of a procedure or function declaration, except that the word FORWARD replaces the procedure or function block.
In effect, we separate the heading from the block.
take a took at the procedure DrawLine:
For example,
PROCEDURE DrawLine (Character
:
CHAR; Linesize, AngLe
REAL);
FORWARD;
Page 6—10
DECLARATIONS AND DEFINITIONS
Now a function or procedure declaration may appear procedure or function.
the actual procedure or definition btock appears, preceded by the name of the function.
For ecample: that inv9kes the
Later within the dectaration part of the program,
PROGRAM TaxReturn;
C This program computes tac returns.
asks if the user wants instructions (short or
First it
long). )
VAR
Short
BOOLEAN;
Query
: CHAR;
PROCEDURE Display(Short
:
BOOLEAN);
BEGIN C Disptay }
C This is the procedure that actual.I.y
Instructions.
disptiys the
It prints a long or a short
file, depending on the value of Short. )
S
END C Display )';
PROCEDURE
FORWARD;
Printlnstructions (Short
BOOLEAN);
C The forward reference! }
FUNCTION AskAnswer (Query
: CHAR)
:
BOOLEAN;
BEGIN C AskAnswer }
AskAnswer
:
FALSE;
IF Query = 'Y' OR Query &y' THEN AskAnswer :: TRUE
ELSE IF Query = 'V THEN PrtntInstructlons (Short);
END C AskAnswer Y;
PROCEDURE Printlnstructions;
BEGIN C Printlnstructions }
Short := FALSE
C Initialized to long instructions. };
WRITE('Do you want short Instructions? V or N:');
READLN (Query);
IF AskAnswer(Query) THEN Short
:
TRUE;
Display(Short)
END C Printlnstructions );
BEGIN C Main Program }
WRITELN('We''re going to compute your tax return.'); WRITELN;
WRITELN('At any time in this program, you may review the instructions');
WRITELN('by answering anyV or,N question with a
WRITE('Do you want instructions? CV or N): ');
REAOLN(Query);
IF AskAnswer(Query) THEN Printlnstruct4ons(:Short);
WRITE('Do you want to average? (V or N): '); READLN(Query);
IF AskAnswer(Query) THEN WRITELN('OIC, We''l.t average.');
CNow, compute taxes...
S
END C Main Program
1-.
DECLARATIONS AND DEFINITIONS
Page 6—11
Note that when the procedure block
Function
AskAnswer, we did not procedure, since the procedure heading appeared reference
Printlnstructions include the appeared after the formal parameters for that at the time of the forward
6,6,4
Formal Parameters
We would like to include a word here on formal parameters.
Parameters are variables used within a function or procedure,
Pascal greatly extends the usefulness of your routines by allowing your program to supply those values at the time that you invoke your function or procedure,
This means that you can use your routines in data,
Parameters a wide variety of situations, on a wide range of give your functions and procedures a way to communicate with the program that calls them,
The variables that are specified at the time you procedure are called the "formal parameters," the actual invocation of your routine are called
For example, given the function heading: defi
The the ne your function or values you supply with actual parameters"
FUNCTION Salary(Takehome, Gross
:
REAL)
:
REAL; the formal parameters are the variables Takehome and Gross,
When we invoke that function we might do so using constants:
Raise : =Sa La ry (183, 250) or, we might use variables which contain those values
Raise: 5a lary (Net,Tota U;
Note that the variable identifiers we use as formal parameters do not have to be the same as the identifiers for the actual parameters.
You can think of the formal parameters as "placeholders" for the actual data which will he used,
The actual parameters are "plugged into' the formal parameters in the same order as they appear in the routine invocation, (For instance, in the example above, Net takes the place of Takehome, and Total takes the place of
Gross,)
The total formal parameters, number of actual parameters must match the number of
6,6,4,1
Value Parameters — The formal parameters we have seen in our examples above were
all
procedure,
When we left the used within the routine,
Then when we to pass variable information into the function or function or procedure, the value of the variable we passed into the routine was not actually changed, even though might have been procedure made a copy of the calculations, variable was modified unchanged and
In effect, the function
used the copy for
left the routine, the original value of
it
or
its
the
Page 612
DECLARATIONS AND DEFINITIONS
This type of variable is called a "vaLue variables or expressiOnS parameter" Value parameters may be
664 Reference Parameters procedure or
It sometimes happens that you function to actually modify a variabie values you could return would be the single would
(Otherwise, the only value returned by a like
function)
a
To
tell
a function or procedure not to use a copy of a variable, hut to use the variable itself, include the VAR keyword in front of the parameter
For cx amp Ic:
InputString:STRING;PageWidthREAL)REAL
FUNCTION Justify(VAR which might modify the string InputString by inserting blanks so that equaled PageWidth parameter like InputString is called a reference parameter' it in length, and returns the number of blanks inserteth
A
Another way of looking at value parameters and reference parameters is in the case of value parameters we are really dealing that with two different sets of variables: those outside the routine and those insideS
In the case of reference parameters, we are dealing with only one set of variables
Reference parameters must be variables
6.7
EXTERNAL DECLARATIONS
AlphaPascal provides an external library of procedures and functions
This collection of useful routines is available for use by your progranL You may own external libraries
To tell AlphaPascal that you are also write your going to use a function or procedure that is in a standard library other than
STDLIB, you must precede the declaration of that with the keyword EXTERNALS
For example: function or procedure
EXTERNAL FUNCTION Graph (X,Y
:
REAL)
:
REAL; or:
EXTERNAL PROCEDURE PrintLine (Line
:
STRING);
You do not include the procedure block or function block, since the actual
definition of the routine is in the external library
Besides identifying procedures and functions within your program that are defined in an external library, you will use the external declaration to designate elements
For example, suppose you have a main program which
will
be that linked appear in files that are not a main program file together to form file and one program three other
"Program Structure," for information on main program and nonprogram
files
(See Section SA,
files)
Within one file you may well want to use a procedure, function, or variable that was declared and defined in another file, number of fi les together into one program, each
If you are going to link a
file
must contain an
S
—
DECLARATIONS AND bEFINITIONS
Page 6—13 external declaration.., for every element element was declared and defined in another
it
needs
to reference, If that
file.
For example, if the variable CustomeriD need was declared in file File3, and you to reference that variable in File2,
FileZ contains the external decLaration:
EXTERNAL !&
There are some declarations:
CustomerlD
:
STRING; things you should keep in mind when making external
1.
2.
You may not externally declare labels, copstants, or types.
need
If you to have common definitions of these Items, use include files.
For Information on include files, see Section 4.3.2.2, "The Include
Option ($I).'
If you are going to use data
files
in your program, the declarations for those data files must be in the main program file.
(That
is,
data program file.) files may not be externally declared in your main
3.
You must be very sure declarations exactly match the declarations.
that the types given in your types given In the original main
For example, If one file has the declaration: external
VAR Network
:
CHAR; the external declaration in another file for that variable must specify type CHAR:
EXTERNAL VAR Network
CHAR;
CHAPTER 7
DATA TYPES
Weve each already mentioned that a variable is a symbol that can represent more than one data value,
Weve also said that you must "declare the type" of variable used in a program.
This chapter discusses the idea of data type," and the various data types available in Pascal,
A data type describes the kinds of values that a variable can assume, For example, if the variable CustomerlD can assume only numeric, integer values, we say that its data type is "integer,"
Some languages allow you to let one variable assume a variety of types, (For example a variable could have the integer value 34 at one point, and the real value 34,56 at another point,)
Pascal, on data type, the other hand, allows each variable to assume only one kind of
Pascal requires that you declare the type of data that a variable can assume,
This results in several advantages: 1) you can always deduce the type of values a variable can assume by reading the program; you do not have to run the program to figure it out; 2) certain operations may only he done on specific data types; having to declare your variables aids the compiler in making sure that you are not performing an mixing variables of different data types,
(For
illegal
example, operation you may on variable;
3) the compiler is able to make sure that you are not improperly not multiply a real number by an integer and get an integer result,) Once a can be applied to that variable, the type of values it can assume, and the standard procedures and functions that can he used on it, a variable has been assigned a data type, we have automatically defined the operations that
Several data types have been predefined for you by AiphaPascal; these are called
"standard data types,"
The AlphaPascal standard data types are:
INTEGER, REAL, BOOLEAN, CHAR, STRING, and TEXT,
Data types are grouped into two categories: simple and structured,
A simple data type is type a "scalar" type, contains the set of
A scalar data type is one that contains a set of elements, and those elements are ordered,
For example, the INTEGER data instance, "2 is less than "1 which is less than 0 which is less than is less than 2, and so on, whole numbers, These elements are ordered; for
1 which
Page 7—2
DATA TYPES
Structured data types are more types.
If you were to create your own up of simple data types.
sophisticated than the simple, scalar data structured types, they would be made
Pascal supplies a set of keywords
(SET,
ARRAY,
RECORD, and FILE) that you can use to build str(jctured types.
7.1
SIMPLE DATA TYPES
Simple data types can either be the
REAL,
BOOLEAN, pre—declared simple data types (INTEGER, and CHAR), or they may be types defined by you.
If defined by you, a simple data type is either a scatar type or a subranqe of another, already defined scal.ar data type.
7.1.1
INTEGER
Integers are whole numbers (that is, numbers with no fractional part).
Alphapascal allows you to use integers in the range of —32767 through 32767.
They are stored by the computer as one—word, signed 2's complement binary numbers.
These are integers:
32000
!450
MAXINT
+56
(Remember that the pre—declared constaflMAXINT is
AtphaPascat can represent, 32767.) the largest integer that
The standard identifier
INTEGER example:
VAR designates the
Ellipse, Counter, Control
:
INTEGER; integer data type.
For
The operators that have been defined for
Integers are: addition operator
IN; and, the relational operators.
(+); subtraction or sign inversion, C—); multiplication (*); integer division—— that is, divide and truncate—— CDIV); modulus (MQD); the set membership
Using other operators (for example, the real division operator, I) on integers causes the compiler to generate an error message.
There are many functions that accept INTEGER arguments.
(See Chapter 12,
"Mathematical Functions," for a list of the trigonometric, hyperbolic trigonometric, and mathematical functions.)
Two other functions often used on INTEGER data are the PRED and SUCC functions.
PRED returns the predecessor element of the data type; SUCC returns the successor element of the data type.
For example, given three variables, ONE, TWO, THREE of type INTEGER, and ONE =
1,
TWO
2, and THREE
(See Sections 11.1.6 and
3:
PRED(TWO) returns
1; $IJCC(TWO) returns 3.
DATA TYPES
11.1.8
for information on PRED and 5(4cc.)
Page 7—3
7.1.2
REAL
Real numbers are deciunat numbers that may contain a fractional, part.
noted in Section
As
5.6, "Notation," we can represent rest numbers either in decimaL notation or In scientific notation.
These are reaL numbers:
9.3
—56.7812
7.03E+5
+45.0
1 .03E—3
The computer stores real numbers as three—word fLoating point numbers significant to
11 digits (12 for reaL numbers in which the fractional part is zero or less than 1E12), with an exponent range of roughLy 1E—37 to 1E37.
The standard identifier REAL designates the reaL number data type.
example:
For
VAR
Mean, Median, Variance
:
REAL;
The operators defined sign Inversion
(—); for real numbers are: addition (+); subtraction and muLtipLication
(*); real division (I); and, the reLationaL operators.
Many functions accept REAL numbers as arguments.
Note that you may riot use the PRED and, SUCC functions or the set membership operator IN on REAL data.
7.1.3
BOOLEAN
The
Bootean data type contains two elements: TRUE and FALSE.
These elements are ordered so that FALSE <
TRUE.
(And, SUCC(FALSE) returns TRUE.) FALSE and
TRUE are pre—dectaréd constants.
A Boolean variable represents a LogicaL true or faLse vatue.
For example:
IF Month =
ApriL
THEN Spring
:
TRUE
In the statement above, Spring is a Boolean variable that can assume the vaLues TRUE or FALSE.
To designate a Boolean data type, use the standard identifier BOOLEAN.
example:
For
VAR
Query, Female, Employee
BOOLEAN;
The operators defined for Boolean data are; AND, OR, and
NOT.
These called Boolean operators, and produce a Boolean result.
For exampLe: are
Page 7—4
D'ATA TYPES xtY gives a result of TRUE if both X and V are TRUE, or FALSE if
(or both)? are FALSE.
either X or V data
When we use the relational operators on INTEGER, REAL, CHAR, or STRING types, the result is always of type
BOOLEAN.
You may use the PRED. and SUCC functions on use the set membership operator, IN.
data of type BOOLEAN, and you may
You may also use the ORD function:
ORD(FALSE) = 0
ORD(TRUE) =
1
.
7.1.4
CHAR computer recognizes a specific set of characters that it can represent.
The of the Alpha Micro computer, this ordering, is
In the case
:tttd
the
"ASCII coltatig set of characters is called the "ASCII character set." sequence," and the
Character
(For a list of the ASCII characters, see Appendix B,
"The ASCII
Set .")
A
CHAR variable contains one ASCII character.
To indicate an element of
CHAR data type, enclose it in single quotes... For example:
VAR
MenuChoice
:
CHAR;
MenuChoice
:
'A';
The relational operators have been defined for use on CHAR data.
that
A
Remember
< B because of their position in the ASCII collating sequence.
You may also use the set membership operator, IN on data of type CHAR.
To designate data as type CHAR, use the CHAR standard identifier.
VAR Initial
:
CHAR; or:
TYPE
Character
VAR Item
CHAR;
Character;
Because CHAR is a non—REAL scatar type, you can use the
SUCC and
PRED functions to identify predecessor and successor eleaents of the type.
For example:
PRED('B') returns an 'A'.
You can also use the ORD function to determine the position of the character In the ASCII character set.
(For more information on PRED,
SUCC, and ORb, see Chapter 11, "Miscellaneous Functions and
Procedures.")
DATA TYPES
Page 7—5
NOTE: Remember that CHAR data is only one ASCII character.
Another standard data type exists, STRING, which reprsents a coLlection of CHAR data.
example:
'A' is
CHAR data, but 'ABCD' is STRING data.
For
For information on
STRING, see Section 7.2.3, "STRING."
7.1.5
User—Defined Scàlar
Pascal allows you to define your own scatar types.
To do so, use the type declaration statement.
You will supply the name of the data type, and the elements of which It is composed.
For example:
TYPE Spectrum =
(Violet,Blue,Green,Yellow,Orange,Red);
Just like any other scalar type, your data type consists of ordered elements.
This ordering is reflected by the order in which you list the elements in the type declaration statement.
For exampLe, Qiven the statement above, Violet < Blue < Green, and so on.
?ou can then declare and use a variable of the data type you have defined.
For example:
VAR Colors
:
Spectrum
IF Colors =
Red THEN WarmColor : TRUE;
The relational operators have been defined for user—defined scalar types, and return a Boolean result.
Internally, the computer stores each of these elements as an integer value.
(For example, in the example above Violet is
0, Blue is 1, and so on.)
You may not use scatar types In I/O operations.
For example, this statement is illegal:
WRITE (Yet low) if Yellow is an element of a user—defined scalar type.
However, you could say something like:
IF Colors =
Yellow
THEN WRITE('Yellow');
Note that Colors is a variable, but Yellow is a constant of the scalar type
Spectrum (just as the number 2 is a constant of the scalar type INTEGER).
You may only use relational operators and the set membership operator, IN, on an element of a user—defined scatar type.
NOTE: Rather than using a type declaration followed by a variable declaration, you may combine both statements into one variable declaration when defining your own data types.
For example:
VAR WaveLengths,Colors
:
(Violet,Blue,Green,Yellow,Orange,Red);
Page 7—6
DATA TYPES
However, If you are going to have more than one declares variables variabLe declaration that of that type, you must have a Separate type declaration statement :lnstead.
You may use the ORD, PRED and SUCC functions on user—defined
For example, given our example above: scalar types.
ORD(Violet) =
0
ORDCBIue) =
1
SUCC(Vtotet) =
PREeCorange) =
Blue
Yellow
7.1.6
user—Defined Subrange
Pascal allows you to define a subrange of a previously defined data type.
For example, given the data type Spectrum to only access the first three above, suppose you want a variable colors elements of that type,
Viotet,
Blue, and Green.
You could define a subrange scatar type:
TYPE Coldcolors =
Violet
..
Green;
You may define a subrange of any user—definedor standard scatar type except type REAL.
Use the type declaration statement in this format:
TYPE Type—name = lowerlimit
..
uppertimit;
The symbols
'.." tell
Pascal that you are establishing a sthrange.
Upperlimit and Lowerlimit are the beginning and ending elements of the subrange.
For exampte:
TYPE Decimal =
'0'
..
'9'; tells
Pascal that we values in the range of want to define a type named Decimal that can assume
O' through '9' of the standard data type
CHAR.
We can then declare a variable of that type:
VAR Number
:
Decimal;
NOTE: You may also directly declare a variable to of a subrange without using a type declaration statement.
For example:
VAR Number
:
'0' ..
'9';
7.2
STRUCTURED DATA TYPES
Structured data types are built up of simple scatar data types.
keywords can be
Several used to define structured data types: ARRAY, RECORD, SET, and FILE.
DATA TYPES
Page 7—7
You may define your own structured data types in much the same way that you were able to define simple scalart"pes.
(SeeSection 7.1.5, "User—defined
Scalar.') Two structur'éd types have been pre—dectared for you: STRING and
TEXT.
7.21
Packed Data Types
Before we discuss the various structured data types available to you, we'd like to digress for a moment and talk bout how the computer represents data types in memory.
Structured data types sometimes require quite a bit of room in memory.
For example, consider how many memory locations must be at located for a structure such as:
ARRAY CQ..1O,0..10,0..1O,0..10] OF CHAR; where more than 10,000 elements must be handled.
ARRAY data
(NOTE: We discuss the type in Section 7.2.2, "ARRAY.') It is often the case that only one element of such a structure is stored in one memory location, even though there physically may be room for more.
To hep minimize memory use,
Pascal allows you to create "packed' data structures, in which the data in the structure are packed together in a minimum amount of space.
To create a packed data type, include the keyword statement:
PACKED in your type declaration
TYPE Type—name = PACKED data. type
For example:
TYPE CustomerlD = PACKED
ARRAY C1..50] OF CHAR;
You may also pack records by preceding the keyword
RECORD, with the word
PACKED.
Only the array or record immediately following the PACKED keyword is affected, and any nested arrays or records must be explicitly packed.
As one example of the efficiency you can sometimes gain in packing data, consider the following data structure of type RECORDi
TYPE
Date =
RECORD
Month
:
(Jan,Feb,Mar,Apr,May,Jun,Jul,Aug,Sept,Oct,Nov,Dec);
Day 1..31;
Year
: 0..99
END;
Unpacked, the data above takes up three words of memory; packed, it takes up only one word.
NOTE:
Some types of data cannot be packed (e.g., real numbers), and the keyword PACKED in the type declaration for such data types has no effect.
Page 7—8
D*TA TYPES other data type.
than any
Your program does not need to handle a packed data type differently
(NOTE: Standard Pascal requires that you use the, UNPAcK and that your program can read and for
PACK. standard procedures to convert you automatically.
write.
between packed format and a format
AlphaPascal performs this
In fact, AlphaPascal does not conversion support the PACK and
UNPACK procedures.)
Although you do save memory space by fact that your program wit.I.
run structure, because of the time packing a data type,, be aware of the slower when it handles such a data required to unpack and repack data.
7.2.2
ARRAY
An array has a fixed number of components which may be accessed In any order by referencing the location of the element within the array.
To reference an element of the array, you give the name of the array, and the array index
(sometimes called a subscript) which selects the location within the array whose contents you want to access.
The subscript appears after the array name in square brackets:
Array—namet mdcxi, Index2, ...
'thdexN
3 where each index is a simple type.
For example, suppose the array PartNos contains thirty part numbers, and you want to see what the twentieth one is.
You would access the twentieth location in the array by saying:
WRITELN(PartNosC2O]); or perhaps:
WRITELN(PartNost2 +
Offset);
Alt elements of an array must be of the same data type.
Your declaration of the array must include the data type of' the etements of the array, and the data type of the subscripts by which' yout 'witi access eLements of that array.
(Declaring the type of the subscript tet:ls Pascal how many elements the array wilt contain.) For example:
TYPE MonthTotats =
ARRAYC1..2O]
OF REAL;
The statement above tells Pascal that you are defining an array type named
NonthTotals whose elements wilt be real numbers, and that the locations in that array will be accessed by refering to the numbers 1' through 20 (e.g.,
MonthTotals(1], MonthTotalsC2], ...
MonthTotalsC20]).
The subscript data type can be any scatar type except REAL.
Although this field will often be of type INTEGER, it doesn't have to be.
For example;
TYPE ComplaintNum =
ARRAY
Esobsoffice ..
PaulsOffice]
OF INTEGER;
S
DATA TYPES
Page 79 where such
BobsOffice, PaulsOffice is a subrange of a userdefined scalar type, as (RohinsOffice, BobsOffice, PaulsOffice, BilLsOftice),
After you have declared an array type, you may now declare a variabLe of that type.
For example:
VAR Problems
:
ComplaintNum;
Pascal also allows a shorthand form that permits you to combine the type and van able declarations:
VAR Problems
:
ARRAY [BobsOffice PaulsOffice] OF INTEGER;
One of the features that help make arrays so useful is the fact that subscripts may be expressions.
This allows you to access elements of the array using variables for the subscripts
For example
PROGRAM Squareit;
VAR
Square
:
ARRAYE11O] OF INTEGER;
Counter
:
INTEGER;
BEGIN { Squarelt )
öflnter
:
1;
WRITELNCSquares of the integers
1
FOR Counter
:
1
TO 10 DO to 10 are:
BEGIN
SquarelCounter] : = Counter*Counter;
WRITELN (SquareiCounter])
END;
END {Squarelt }
The small program above creates array Square of ten elements.
The FORDO loop increments the variable
Counter from
1 to 10, accesses the array location indexed by Counter, and writes the square of Counter into that location of the arrayS
(For example, location SquareES] contains the number
5*5, or
25)
You can use a similar type of loop to retrieve data from an array.
NOTE: Sometimes you can fill an array without using loops
For example:
InvoiceNumflAfl := InvoiceNum[ B]; accomplishes the same thing as:
FOR
I :=
I
TO
5
DO InvoiceNumCAv,I]
:
InvoiceNumVB,I];
Page 71O
DATA TYPES
7221 MultidimensionaL
Arrays
UntiL now our discussion has been of
"onedimensional" arrays; that is, arrays with just one index
Pascal also allows you to constrUct arrays with an unlimited number of dimensions
(You might consider a multidimensional array
Suppose you want track of a fiv&element array, each element of which is in turn a fiveelement array: as an "array of an array") To declare such a structure, include additional subscripts in the to keep declaration
TYPE InvoiceNums ARRAYPAiEt] OF ARRAYE15J OF INTEGER;
Pascal also allows a shorthand form:
TYPE InvoiceNums ARRAY[AiE,15J OF INTEGER;
The statements above create a two-dimensional array of
25 elements
Each element is referenced by a pair
of subscripts
If we wanted to make a pictorial representation of our array InvoiceNums, it might look something like this, with the Xs representing integer numbers contained in the array:
I
K X
A
X
X X
X
X
X
X X
C?]
C
X X
X
X
D
X
X
X
X
X
X
X
X
X
X
If we wanted to access any number in the array, we would have to specify the subscripts that designate the proper
1ocation (In the example above,
tAE designate
array
"rows"; 15 designate
array
"columns")
The subscripts columnS for a twodimensionai array must identify the elemenUs row and
For example, to identify the element marked with a question the table above, we would ask for Row C, Column 4: mark in
Invoi ceNumsl C
,4]
The number of dimensions an array may contain is limited only by the room memory.
in
723 STRING
We have already mentioned the data type
CHAR.
A contains a single
ASCII character variable of type
CHAR
However, we often need to refer to collections of characters (such as words, names, or addresses) rather than just single characters
DATA TYPES
Page
7—11
The standard data type
STRING allows you to declare variables that contain group (or "string") of ASCII characters.
For example: a
VAR Accountlp
:
STRING;
The default maximum string length is 80 characters, but you can set the string length maximum to from 1 to 255 characters,
To set maximum string length, follow the brackets,
For example: identifier
STRING with an integer constant in square
TYPE OrderlD
=
STRING[25J;
The STRING data type is approximately equivalent to:
TYPE
STRINGCNJ = PACKED
RECORD
LEN:
0, ,255;
TXT
:
ARRAY C1,,N] OF CHAR;
END;
If N above is given above purposes; you
The computer front of the omitted, STRING defaults to size
80, for
(NOTE:
The structure
STRING is approximate, and is only given for illustrative cannot access the length of string X by referring to X,LEN,) stores strings with one character per byte, and one byte at the string which tells Pascal how long the string is,
7,2,4 TEXT
The standard data type TEXT is equivalent to the type FILE OF CHAR,
For example, suppose you want to declare and open a text file, you could say:
PROGRAM ReadListing;
TYPE
ListFile = TEXT;
VAR ProgramList
:
ListFile;
BEGIN { ReadLi sting }
OPEN (ProgramLi st, ACCNT1 ,DAT
,OUTPUT);
{ read data from file }
END { ReadListing 3-,
NOTE:
In the example above, it would also have been valid just
ProgramList
:
TEXT,
(Note to users of previous versions of the file type INTERACTIVE is no longer needed or supported, occurrences of the identifier INTERACTIVE with TEXT, or at the program re—define
INTERACTIVE (eg,,
TYPE INTERACTIVE information on type FILE, see Section 7,2,6, below,) to say:
AlphaPas
Replace front of
TEXT),)
VAR any your
(For
Page ?—1Z
DATA TYPES
7,2,5
SET
Sets give you a very-.! efficient y of handLing certain kinds of information,
Although, they are not exactLy analogous, you might think of sets as a kind of packed Boolean array, to be
The use of sets allos complex logical expressions written concisely, and also gives a more flexible way of performing
logical tests,
For example, instead of the cumbersome statement:
IF (Character = A) OR (Character = B') OR
(Character = t') OR (Character =
OR (Character
E')
THEN Flag
:
TRUE; using sets, you can simply say:
IF Character IN [A,EJ THEN Flag
:
TRUE;
To define a set type, use the type declaration statement,
Every element of the set must be of the same type, and that type may not be structured,
You must specify the name of the set data type, and the base type of that set:
IYPE Identifier = SET OF hase"type;
For example:
TYPE Player = SET OF 1,,5;
Once you have defined the set, you can now declare a variable of that type:
VAR Piece
:
Player; which can assume one or more of the values of that set,
Pascal also allows a shorthand declaration:
VAR Piece
:
SET OF 15;
The symbol
£
J is the set constructor operator, expressions of the form:
[expressi on]
It takes a or:
[expression ,, expression]
For example, given that
Y assignment statement: is of type
SET, the following is a
list of
valid
Y
:
[X, X+5
, ,
X+7J;
It assigns the element X and the elements X+5 through Xi-7 to the set Y,
You may mix sets of the same base type,
For example:
DATA TYPES
Page 7—13
VAR
—
X
:
SET OF 'A'.. 'X';
5V
: 1Ff
BEGIN
Y:Y+X;
END.
You may use modifying assignment operators on sets.
(So, for example, you could rewrite the statement above to: Y +)Q.)
The operations that you can perform on a set are those defined by set theory: set union (+); set difference
()r; set Intersection (*); set equality (); set inequality (0); set inclusion
(< and >); and, set membership (IN).
The empty set, "E)', is a valid set.
If we define a type Newset that is a set of integers:
TYPE NewSet ai2L1
..
10;
VAR
Seti
:
Newset;
Set2
:
Newset;
Result
:
Newset and then assign values to the sets Seti and SetZ:
Seti
:
Set2
:
[5,6,7,8,9);
We can use the sets Seti, Set2, and Result to talk about the operations you can perform on sets:
+
Set
Union. An element is contained In the union of SETI and
SETZ if and only if it is an element of SET1 or SET? or both.
For example:
—
*
Result
:
Seti +
Set?
{ Result is the set C1..9) )
Set
Difference. An element is contained in the difference of two sets if and only if it is an element of SEll but not an element of SET?.
For example:
Result : Setl —
Set?
{ Result is the set C1..4] }
Set
Intersection.
An element is contained in the intersection of two sets if and only if it is an element of both
SETI and
SET?.
example:
For
=
Result
:
Seti *
Set?
C Result is the set [5) }
Set
Equality.
Seti
=
Set2 is TRUE if and only If every member of
Seti is also a member of Set?, and every member of
Set?
is also a member of Setl.
S
Page 7—14
DATA TYPES
>
Result :s
Seti
=
SetZ
C
Result is FALSE )
0
Set
Inequality.
Seti 0 SetZ is TRUE if and only if Seti
Set2 is
FALSE.
<n
Result :=
Seti
0 $et2 'C Result is TRUE )
Set
Inclusion. The relation Seti <=
SetZ is TRUE if and only if every member of Seti Is also a member of Set2.
In other wOrds, Seti
<
SetZ is TRUE"tf Seti Is included In Set2.
Result :=
Setl
<
SetZ
C Result is FALSE)
IN
C6,93 <=
Set2 is TRUE.
Set
Inclusion.
The relation Set I >=
SetZ is TRUE If and only if every member of Set2 is also a member ofSetI.
In other words, SetI
>=
Set2 is TRUE if Set2 is Included In Seti.
If X <= V is TRUE, then
V >
X is TRUE.
Set
Membership.
If
X is of the type declared as the base—type of
SetI, then XIN Seti is TRUE if and only if 1 is contained in
SetI.
For example:
Result
;
S
IN Seti
C Result is TRUE )
'C Result is FALSE )
Result 26 IN Seti
The
IN operator takes as aJft argument a simple data type variable or constant (e.g., CHAR or INTEGER); the right argument must be a set of that data type (e.g., set of CHAR or set of INTEGER).
Below is a small sample program that uses sets:
.
DATA TYPES
.
Page
7—15
PROGRAM;
VAR
Y1,Y2,V3,N1,N2,N3
CHAR;
BEGIN
Query
:
CHAR;
Yes,No
:
——
Yes
:
E'Y']; No := ('N'];
WRITELN('The only valid response to a YeslNo question is Y or N.');
WRITELN('We''l$. let you add yout own answers.'); WRITELN;
WRITELN('Entef' three one—character symboLs that can stand for YES ');
WRITE('(separate them with a space, not a comma): ');
READLN (Yl ,Y2,Y3);
Yes := CY1,Y2,Y3] +
Yes;
C Add user—defined symbols to Yes )
WRITE('Now, enter three symbols for NO:
');.
READLN(N1,N2,N3);
No :
CN1,N2,N33
+
No;
C Add user—defined symbols to No }
WRITELN;
WRITE('Let''s test this out.
Enter a Yes or No answer:
');
READL.N(Query);
WRITELN;
IF Query IN Yes THEN WRITEt.N('Yes!')
ELSE iT
Query
IN No THEN WRITELN('No!')
ELSE WRITELNT'I didn''t understand you.')
END.
7.2.6
FILE
A file is a structured data type that contains a sequence of elements of the same type.
Since you can only access one element at a time, files might seem much like an array.
The important difference is that file are associated with
AMOS disk files, and so can store data permanently beween program runs.
Files are the means of communicating with devices such as terminals and printers.
In addition, unlike other structured types, the size of a file does not have to be declared, and may be of any size supported by the AMOS file structure.
Files typically hold data of type CHAR or they contain records (see Section
7.2.7, "RECORDS").
Use the type declaration to declare the data type:
TYPE identifier =
FILE
OF base—type:; where Identifier is the name you want to assign to that type of file, and base—type is the data type of the data in the ttle.
To use this type of file, you wilt have to define a variable of that type:
VAR file—identifier identifter;
Page 7—16
DATA TYPES
The file—identifier acts as a communication channel.
Using commands such as
OPEN
(see
Section
10.2.12, "OPEN'), you can associate the file—identifier with an attual AMOS file, and transfer data between your program and the
disk file.
Rather than using a type declaration followed by a variable variable declaration statements: declaration,
AlphaPascal also permits you to use a shorthand method of combining type and
VAR
NewData
:
FILE OF INTEGER;
Remember that you must use one of the functions or procedures discussed
Chapter 10, in
"I/O Functions and Procedures," to tell AlphaPascat which AMOS file you want to associate with the tile variable that you have declared.
NOTE: The chapters in this book, especially Chapter 10, frequently use the term
"file—identifer." identifies
the Pascal associated.
Other books that describe Pascal may just call this
identifier "file." The file—Identifier is not
the same thing as a specifying the Pascal data structure with which the actual file
wilt fite
specification.
The file specification icThiWifies the actual AMOS disk file that you want to read data from or file write variable.
data
Think
to.
The
file-Identifier
of the file—identifier as
be
Several of the functions: you can use to handle files accept a
file—identifier and a file specification.
Por example, the FSPEC procedure accepts three arguments: the default extension.
For instance:
file—identifier,
an
AMOS fitespec, and a
FSPEC(Filel,'ACCNTS,''DAT'); where Filel is the file—identifier, and ACCNTS.DAT is the AMOS file we want
to associated with that file variable.)
The standard identifier TEXT has been pre—dec:lared for you; this Identifier is equivalent to FILE OF CHAR.
(See SectIon 7.2.4, above, for information on TEXT.)
7.2.7
RECORD
A record is a data structure that consists of a number of components (called
"fields").
Unlike arrays, the record elements do not have to be of the same type, and you access the elements by name, not by subscript.
You can use records to develop very sophisticated data structures
(e.g.,
array of
records, file of records, pointers to records).
When you declare a record type, you are defining a template for a: group of variables that contain related information, but which do. not have to be of the same provide the name of the record, and names and types that record: type.
To define a record, use the type declaration.
of the
fields
You will within
S
DATA TYPES
TYPE
identifier =
RECORD fieidname,
, ,,fieid"nameN fieLdname,,fieldnameN
;
;
fiel&'typel;
field—type2;
Page 717 fieLdname, ,field'nameN
;
fieldtypeN;
END.;
For example, a record to represent a date could be defined as:
TYPE
Date =
RECORD
Day
;
(Jan, Feb,Mar,Apr,May,Jun,Jul,Aug,sept,oct,Nov,Dec);
1,31;
Year
;
INTEGER
END;
You may then declare a variable of type Date;
VAR Deadline
;
Date;
Such a variable day, and the year.
you want to do so.
would contain three pieces of information; the month, the
However, alL the information may be treated as a unit if if several fields share the same type, you may
list
them on one separated by commas, You may also nest record definitions,
For example;
line,
TYPE
Credit =
RECORD
Finances
;
RECORD
Checking, Savings, Loans
END;
END;
Name
Birth
;
;
STRINGC5OJ;
Date
;
INTEGER;
After example; defining a record, you may then declare a variable of that type.
For
VAR
Customer
;
Credit;
To select a fieLd of a record, use both the name of the record variable and the name ot the field, separated by a period,
For example;
It Customer,Name = Smith, John C, THEN CheckCredit;
You may assign the value of record to another,
For example, given;
VAR
Customer, Employee
;
Credit; you may assign the contents of record Customer to record Employee;
DATA TYPES
Employee
:
Customer which is equivatenVto:
Emptoyee.Finances
Customer.,Finances;
Emptoyee.Name := Customer.Name;
Employee.Birth
:
Customer.Birth;
Page 7—18
7.2.7.1
variant Parts —
Records of the same type do not necessarily have to contain the same fields.
Suppose, for example, that you are maintaining a record of customer information in which one of the fields tells you whether or not the customer has a car.
Car
:
Boolean;
If, in fact, the customer does have a car, you might want to maintain another set of information (such as ticénse number, model, year of make, etc.), but it doesn't make sense to fill In that information for a customer who doesn't have a car.
Pascal allows you toattocate fields which may or may not exist, depending on the value of another field.
These fields, which act as variations to the basic record structure, are called
"variant" fields.
The variant field definition takes this form:
CASE field—type OF
Case—liffel...,Case—labetN
:
(fleld—tisti);
Case—tabel...,Case—tabelN: (fleld—tist2);
S
Case—label.. .,Case—labelN: (fietd—listPl) or:
CASE case—field—Identifier
: field—type OF
Case—label...,Case—labelN
: iTield—tisti);
Case—label...,Case—labelN
:
<field—list2);
Case—label...,Case—labetN
:
(fietd—listN)
Several case
Labels may be written on one line, separated by commas.
The list of variant fields must be enclosed with parentheses.
(If no variant fields are to be used in the case of a certain value, empty parentheses may be used or the value may be omitted.) If you create a variant part, the variant fields must appear at the end of example: the record definition.
For
.
DATA TYPES
Page 7—19
TYPE
Customer =
RECORD
Name
STRINGC5Q];
Number
: tNTEGER;
CASE Car
BOOLEAN OF
TRUE
:
FALSE
(LicenseNo
:
STRINfI[7];
Model
:
STRINGrIS];
Year
:
INTEGER);
: U
C You may omit this line )
VAR
Query
:
ARRAY Cl. .200] OF Customer;
7.2.8
Pointer Type
Pascal recognizes two categories of variables: static and dynamic.
Static Variables — Static variables are which determine their types and these declared in variable declarations
identifiers.
You use variables are created when the block in which they are declared
identifiers
to refer to the variables.
Static program leaves that block.
Most of the variables shown in this is book executed, are and remain in effect until your
static variables.
used when you know ahead
They can only be of tiffie what the storage requtrements of your program is going to be.
Dynamic Variables —. Dynamic appear value variables are created on demand.
They do not in variable referenced by of type declarations, variable
identifiers.
and so cannot
Instead, dynamic variable of type X has associated with
it
be each variable, and contains the value of the address of the value.
a
X which Is cat led the pointer to X. The pointer to x is used to access the corresponding dynamic
The pointer type is declared via the type declaration statement:
(The
TYPE
Identifier =
base—type; symbol identifies a pointer.) For example:
TYPE
Location = 'INTEGER;
The declaration above establishes a pointer type Location whose pointer variables will point to variables of type RECORD.
To use the pointer type, we must declare variables:
VAR
NewNumber
: Location;
NewNumber is a pointer variable that Is associated with an integer value.
An identifier followed by the pointer symbol, designates the actual value being pointed to.
Therefore, NewNumber pointed to by NewNumber.
Is the actual integer value being
Page 7—20
DATA TYPES
Now, to actually •use the data types we have defined, we must use the NEW function to allocate the dynamic variable:
NEW(NewNumber); creates an unnamed variable of type INTEGER, and stores the pointer to it in
NewNumber.
To access the new pointer, we reference it as
NewNumber'.
(See
Section
11.1.4,
'NEW," for information on NEW.
AtphaPascat also uses two functions called MARK and
RELEASE for manipulating pointer data; see
Sections 11.1.3, "MARK," and 11.1.7, "RELEASE.)
Pascal contains a special pointer constant that indicates that a pointer is not pointing to anything: NIL.
This is useful for indicating special conditions, such as the end of a list.
For example:
EndingNode :
NIL;
The use of pointers gives the Pascal programmer an extremely powerful tool for developing sophisticated structures (for example, Linked Lists).
There are many examples of usefuL applications for pointers.
example, suppose you want to sort an array of records:
As one simple
TYPE Rec
REcoRD
Name
:
STRING;
Data
:
ARRAY tl..5O] OF INTEGER
END;
VAR
X
:
ARRAY C1..20] OF Rec; you would have to perform a great many record moves; a stow and Inefficient process.
If you instead use pointers:
VARX
: ARRAY (1.020]
OF Rec; you only need to sort pointers, which is much faster.
small sample of the use of pointers:
Here is a very
VAR X, V
:
INTEGER;
BEGIN
NEW(X);
Y
:
C :
5;
WRITE(X);
6;
WRITEOC)
WRITE(Y);
{ Note, X and V are pointing to the same location, so output will be 5,6,6 )
END.
A linked list is one example of a useful data structure you can build with pointers.
(You might also consider building doubly linked lists, trees, queues, etc.)
Let's take a took at the linked list and see useful, and how to build one.
why it is so
DATA TYPES
Page 7"21
Each element of a linked list contains: 1) data; and 2) a pointer to the next element of the list,
To change the order of the elements in the list, therefore, you only have to change the pointers, themselves, not the elements
Lets say that you have a sorted array of integers.
If you add another number to the array, you must sort the entire array to get the elements back into the oroper order,
If, however, the numbers are stored as a linked list, adding a new number just entails changing two pointers in the list,
For example:
Listi
NewList
(23) etc,
(32)—"—*(67)-—"—"+' etc.
(40)
To delete an element of the list, you only need to link around it,
Declare a linked list as follows:
TYPE Node =
RECORD
Data
Next
:
END;
:
INTEGER;
Node
Notice that we said that the data portion of the list element will hold integer data; you can use whatever data type you want,
Lets build a simple linked list, and then display it in reverse:
(Changed 30 April 1981)
DATA TYPES
Page 7"22
PROGRAM LinkedList;
TYPE
Pointer =
'Element;
Element = RECORD
Dat a
Next
END;
INTEGER;
Pointer
VAR
I,X
:
INTEGER;
P,List
:
Pointer;
BEGIN C LinkedList }
WRITEVEnter integer: fl;
C Get first number of list
)
READLN(X);
List
:
NIL;
C Initialize list }
WHILE X <> 0 DO C End list when X
0 }
BEGIN
NEW(P);
P ,Data
:
P',Next
:
List;
C Allocate dynamic variable }
C Put number into list )
C Set
List
:
P;
WRITE(Enter integer; fl;
list pointer to next element )
READLN(X)
P :
END;
List;
WHILE P <> NIL DO
BEGIN
P
WRITELN(P',Data);
:
P',Next
END
END CLinkedList },
If
you enter the numbers:
1
2
3 4
Other useful examples would involve deleting elements from a list by upd
5
6 7, you see displayed: 7 inserting elements into
ating the list pointers,
a
6 5 4 3
2
1,
list
and
NOTE; combination with NEW to make use of a
"heap,"
RELEASE
AlphaPascal contains the orocedures MARK and RELEASE which you use in
(See
Chapter
11
stack'like
for information on MARK and RELEASE,) MARK and allow you to oerform very powerful structure called the operations with dynamic variables,
However, they can be dangerous if used unwisely; you should be an experienced Pascal programmer before using MARK and RELEASE,
(Changed 30 April 1981)
CHAPTER 8
EXPRESSIONS
An expression is any combination of operators, constants, and variables.
For example:
function calls,
(238.6 * Invoice + SQRT(TaxBilt))/365
This chapter discusses the legal AlphaPascal. operators, and gives the rules of operator precedence.
We also talk about some special expression handling abilities of AlphaPascal.
8.1
OPERATORS
An operator elements of an expression.
expression is a symbol that directs Pascal to perform an action on the
For example, the addition operator,
+, in the
34+123 tells Pascal to add the numbers 34 and 123.
The operator types in Pascal are: arithmetic,
Boolean,
Another to variables.
relational,
logical, and set.
special operator, the assignment operator, is used to assign values
8.1.1
Operator Precedence
When Pascal sees the various operators in an expression, elements rules in
it
the expression in resporse to those operators.
evaluates the
When more than one type of operator appears in one expression,
Pascal follows a set of called
"operator precedence" in determining which operators to act
upon first,
If the precedence of all operators in the expression is the same,
Pascal evaluates the expression
Pascal evaluates the expression:
from left to right.
For example,
312 + 34 — 20 as:
(312 + 34) — 20
Page 8—2
EXPRESSIONS evaluating the value 312+34 first, precedence of the operators differs, and then subtracting
20 from it.
If the
Pascal evaluates the elements connected by the operator of highest precedence first, and then evaluates the elements precedence, and so on.
For connected by the operator of the next highest example, multiplication has a higher precedence than addition, so the expression:
76 * 54
+
2 tells
Pascal to multiply 76 by 54, expression evaluates to (76 *
54)
+ and then add 2 to that value.
2, or 4106.
The
You can change the order in which
Pascal parentheses.
Pascal always evaluates parentheses first, and then works outward.
processes elements operators by using in the innermost set of
For example, if you want
Pascal to act upon the addition operator first in the previous example, you must use parentheses to tell
Pascal to apply that operator first:
76 *
(54
+
2) that value
This expression tells Pascal to add 54 and 2, and then multiply by 76.
The expression thus evaluates to
4256.
that
NOTE: The operator precedence used by AlphaPascal differs slightly from used by standard
Pascal.
We have changed the precedence to be compatible system.
with that of other language processors on the
Alpha
Micro
Specifically, in
AlphaPascal the Boolean operators are of lower precedence than the relational operators.
The only time you will need to worry about this is if you use expressions that compare unparenthesized
Boolean expressions with relational operators (e.g.,
NOT A =
B).
instance, if you want to be able
(for
If your programs must be written to be compatible with standard Pascal to transfer your programs to another computer system that uses standard
Pascal) use parenthese to make sure that rules of your expressions are evaluated in accord with standard Pascal's operator precedence.
For example, the expression:
NOT A =
B is evaluated by AlphaPascal as: NOT (A =
B).
If you want the expression to work for
AlphaPascal, you should either write it as: either standard
Pascal or
(NOT A) = B or:
NOT (A =
B) to indicate how you wish the expression to be evaluated.
The table below gives the rules of operator precedence for AlphaPascal:
EXPRESSIONS
Highest Precedence
Parenthesized expressions
Sign inversion:
MultipLying operators:
*
— (unary)
I
Adding operators:
RelationaL operators:
BooLean operators:
+
NOT
A ND
OR
Lowest Precedence
DIV MOD
<
> <
>
IN
Page 83
SL2 Assignment Operator
The assignment operator, :=, assigns the vaLue of an expression to a
variahle
(See Section 91,
Assignment Statement," for information on use in a program statementS)
its
Pascal evaluates the expression on the right side of the assignment operator symbol,
The variable on the left side of the assignment operator assumes the value of that expression
Note that
all
variables to values are assigned must have been previously declareth
For example: then which
CardValue
:
9S6 assigns the value 95ó to the variable CardValue
The expression above must have been preceded in the program by a statement such as:
1Y!J. CardValue
:
REAL which values.
declares that the variable
CardvaLue may only assume real number
Most languages (including standard Pascal) only allow the value of a variable to be changed by an assignment statement,
ALphapascaL allows the value of a variable to be changed within an expression
For example:
ZOO + Sum/Total
:
365
Pascal reads the expression above as:
(ZOO + (Sum/(Total
:
365))
That is, Pascal assigns the value
365 to the variable
Total, and then divides the value Sum by Total (which is now 365), and adds ZOO to it
Page 8—4
EXPRESSIONS equal.
The precedence, and that
Remember that the assignment operator has the highest
Pascal evaluates exp'ressions is from left to right when operator precedence precedence," and
Assignment operator has extremely high "left very low "right precedence." the nearest element on the left, but loosely to the remaining consider the following expression: to
That means that it "binds" Itself strongly elements on the right.
To make this Idea clearer,
Result :
10 +
Score
—
Cards
:
32 +
Pairs
—
Singles
The second assignment operator
"swallows up" all binds strongly to the variable of the expression to the right of itself.
Cards, but
This means that
AlphaPascat evaluates the expression above as:
Result :=
(10
+
Score
—
(Cards
:=
(32
+
Pairs)
—
Singles))
That is, Cards Is set to (32 +
Pairs) minus the value of Singles.
value of Cards is subtracted from
10 +
Then, the
Score.
That value is assigned to the variable Result.
As another example of the use of the assignment operator in an expression, consider a situation where you want to initialize a group of variables by
Pascal does not have a multiple assignment setting their values to zero.
statement.
However, the expression;
Averages
:
Total
:
Sum
:
Median
0 causes Pascal to perform a evaluating the expression.
multiple assignment as a side effect of
8.1.2.1
Modifying
Assignment
Operators —
AlphaPascal special operators called "modifying assignment operators." contains a set of
These operators allow you to assign values to variables by modifying the value of the variable instead of replacing that value.
For example, the assignment expression:
RecordCount : 120 tells
Pascal to replace the value of RecordCount with the number modifying assignment expression of the form:
120.
A
RecordCount +
120 tells Pascal to take the value of RecordCount and it.
modify it by adding 120 to
Pascal then assigns this new value to
RecordCount.
We thus modify,
In effect, the expression rather than replace, the value of RecordCount.
above is equivalent to:
RecordCount
RecordCount + 120
.
Page
8—5
EXPRESSIONS
.
The modifying assignment operators. are:
—=
It
Adding modifying assignment operator
Subtracting modifying assignment operator
Multiplying modifying assignment operator
Dividing modifying assignment operator
As another example, the statements:
Number :s
1;
FOR I =
1
TO 5 DO
Number n 2 CSame as 'Number
: compute two to the fifth power.
and 32.
Number *
2')
So, Number takes on the values 2, 4, 8,
16
8.1.3
Arithmetic Operators
The arithmetic operators are:
+
—
+
(unary)
(unary)
Identity
Sign inversion
Addition
Subtraction
Takes INTEGER or REAL operands; same type as operands.
result is
Takes INTEGER or REAL operands; same type as operands.
result is
Takes INTEGER or REAL operands; same type as operands.
result is
Takes INTEGER or REAL operands; result is same type as operands.
*
DIV
I
Mutti— plication
Takes INTEGER or REAL operands; result is same type as operands.
Integer division
Takes INTEGER operands; result is INTEGER.
Real division
Takes INTEGER or REAL operands; result
INGEGER or REAL.
is
Modulus
Takes INTEGER operands; result is INTEGER.
!1Q2.
NOTE:
If you wish to use the sign inversion symbol, —, number in parentheses if another operator precedes the you must enclose the number.
For example, the expression 3 *
—5 is illegal, but the expression:
3 *
(—5) is valid, and evaluates to —15.
SET operands; BOOLEAN result.
Page 8—6
EXPRESSIONS
8.1.4
Relational Operators
C>
C
>
Ct
Equality
Inequality
Less than
Greater than
Less than or equal
(or set inc I us ion
(subset))
Scalar, STRING, SET, or pointer
BOOLEAN result.
operands.
Scalar, STRING, SET, or pointer
BOOLEAN result.
operands;
Scalar or STRING operands; BOOLEAN result.
Scatar or STRING operands; BOOLEAN result.
Scalar or STRING operands; BOOLEAN result.
SET operands; BOOLEAN result.
Scalar or STRING operands; BOOLEAN result.
>
Greater than or equal
(or set inclusion
(superset))
IN
Set membership
First operand is any scalar, second. is its
SET type.
BOOLEAN result.
8.1.5
Logical Operators
NOT
AND
OR
Negation
BOOLEAN operands; BOOLEAN result.
BOOLEAN operands; BOOLEAN result.
Conjunction
Disjunction
BOOLEAN operands; BOOLEAN result.
.
Page 87
EXPRESSiONS
8.1.6
Set Operators
+
Union
*
Given sets of type X, type X.
result is of
Set difference
Given sets of type X, typeX.
result is of jntersection
Given sets o. ype X, type X.
result is of
8.2
CONSTANTS
A constant is a value that doesn't change.
For example, the number a constant, because it can assume no other value.
been pre—defined by Pascal for your use.
They are:
34.5
is
Certain constants have
MAXINT
FALSE
TRUE the maximum integer AiphaPascal. can
Boolean false
Boolean true represent.
You can use these constants as you would any others.
For example;
Initialize CurrentMin to
{ Find the minimum of a list of numbers.
targestpossible number. )
CurrentMin
:
MAXINT;
REPEAT
READ(DataFi le,NewNumber);
IF NewNumber < CurrentMin THEN
CurrentMin :
NewNumber
UNTIL EOF
C Continue tiLt end of file is reached
);
WRITELN('Smallest number is: ',CurrentMin);
Pascal allows you to assign a name to a constant so that you can identify It by name within a program, rather than including the constant itself.
For rather cumbersome)f you had to include the numeric example,
It would be constant 3.14159 throughout a program.
Once ygu use a constant definition statement to assign
3.14159
a name
(such as P1), you can refer to that constant by name.
For example:
WRITELN('The Circumference =
',Pi
*
234);
You may also assign a name to a string constant.
For information on naming constants, see
Section 6.3, "Constant Definitions." For information on the form string and numeric constants may take, see
Section 5.6,
"Notation." not assign a
NOTE:
Of course, constants are not variables; that is, you may constant a new value within the program block.
Page 8—8
EXPRESSIONS
8.3
VARIABLES
A variable is a named symbol that represents a value.
For example, the a range of student identification variable named
StudentlD might assume variety of data.
numbers.
Variables allow a program to operate on a integer
Each variable in a program may assume only one type of value (e.g.,
Pascal requires that you values, real values,
Boolean values, etc.).
declare the data type of each variable before that variable Is used.
(See
7, "Data Types." for
Section 6.5,
"Variable
Declarations," and
Chapter information on data types and declaring variables.)
For information on choosing a valid name for a variable,
"Legal
Identifiers." expression.
A see
Section 5.4, variable identifer may be In
For example, consider the case where we want to the form of an refer to an element in an array:
NewArrayt2,43
:
99;
8.4
IF—THEN—ELSE EXPRESSIONS
Wherever an expression is legal,
AlphaPascal allows
IF—THEN—ELSE expression.
you to include an
This allows you to conditionally evaluate one of two alternative expressions.
The construct takes the form:
IF condition THEN expression ELSE expression
Note that you must include the construct in this way.
For example:
ELSE clause if you use
IF Credit >
(IF
$1 llAmt >
1000 THEN 2000 ELSE 0)
THEN WRITELN('OK, charge it.')
ELSE WRITELN('Sorry, send it C.0.D.'); the IFTHEN
The statement above contains this expression:
ELSE
0.
This evaluates not the variable BlllAmt has a value statement above either evaluates to: greater
IF BillAmt > than
1000.
1000
THEN
Therefore
2000 either to 2000 or to 0, depending on whether or the
IF Credit > 2000
THEN WRITELN('OK, charge it.')
ELSE WRITELN('Sorry, send it C.O.D.'); or:
IF Credit ) 0
THEN WRITELN('OK, charge it.')
ELSE WRITELN ('Sorry, send it C.O.D.');
S
Page S9
EXPRESSIONS
Remember that expressions
Consider the folLowing small
ErrorReport: can also contain program that string constants or \,ariables conditionally assigns a value to
PROGRAM Recoverfl
VAR
ErrorFLag
:
BOOLEAN;
ErrorReport
:
STRING;
BEGIN C Recovery )
ErrorFiag
:
FALSE;
ErrorReport
:
(IF ErrorFlag
THEN An error occurredV ELSE No
WRITELN(ErrorRePOrt)
END C Recovery ).
errorfl
NOTE:
IncLuding an IFTHENELSE construct in an of standard Pascal.
Note that IFTHENELSE may not be used expression
For exampLe: expression is not a feature in a variable
is iLlegaL
(IF X THEN Y ELSE 1)
:
1
B5
CASE EXPRESSIONS
Wherever an expression may appear, expression. This allows you to aLternative expressions
The expression must take the form:
AlphaPascai allows you to include a CASE conditionally evaluate one of
(NOTE: This is not a feature of standard several
PascaL)
CASE value OF valuel
: expression; vaLue2
: expression;
ELSE expression
For example:
WRITE(CASE ErrorCode OF
1
2
:
:
IlLegaL inpuU;
3
:
Number too Large;
Number too smalL;
ELSE undefined errorfl;
Page SHO
EXPRESSIONS
The statement above chooses one the variable
ErrorCode the statement above evaluates to: string to write, depending on
For example, if the vaLue of
ErrorCode contains a value of
3,
WRITECNumber too smaLL);
If ErrorCode contains a value that is not 1,
2, evaluates to:
WRlTEVUndefined error); or
3, the statement
S
CHAPTER 9
STATEMENTS
9.1
ASSIGNMENT STATEMENT
It takes this form:
The assignment statement assigns a value to a variable.
variable expression
Pascal evaluates the expression on symbol, :=.
The values are assigned must have been the right side of the assignment variable on the left side of the assumes the value of that expressionp
Note operator assignment operator then that all previously declared.
variables to which
For example, given that your program previously contatned the statement:
VAR
AccountNum
:
INTEGER; the statement:
AccountNum : 1024+1 assigns the integer value
10Z5 to the variable
AccountNum.
information on the assignment operator, see
Section
8.2,
For more
"Assignment
Operator."
That section also discusses the use of the assignment operator in expressions, discusses the precedence of the assignment operator, and describes the AtphaPascal modifying assignment operators.
9.2
PROCEDURE CALLS
Procedure invocations may appear as program statements.
(For information on procedure parameters, see Section 6.6.1, "Formal Parameters.") Liberal use of procedure calls in your programs illustrates one of the important features of
Pascal—— modularity.
Given the appropriate definitions, a main program can be extremely easy to read.
procedure
For example:
Page 9—2
STATEMENTS
BEGIN C Main Invetitory }
Open#iles(ReceiVng,MaIlutaCt) C Input filespecs for data from Receiving,
Manufacturing departments.
Open files.) ftata(ReceiVng,ManUfaCt)
C Read inventory parts lists );
C Compute which parts we are
FindLow(LOwFile) tow on and write to file. );
C Print list of parts we need more of)
PrintReport(Date,LOWFile)
END C Main Inventory }.
We can tell just by looking approximately what the procedures OpenFites, ReadData, program does.
FindLow, and PrintReport do
The the actual work.
9.3
EXIT
EXIT or function to a calling orogram or routine.
procedure allows you to exit from the program to the monitor or from a
EXIT takes one argument—— the function you want to exit keyword
PROGRAM or the name of the procedure or from.
For example:
EXIT (PROGRAM);
EXIT (Eva tErr);
(You may not supply EXIT with the keyword to exit a program.) program identifier; use the
PROGRAM
9.4
GOTO STATEMENT
The GOTO statement takes the form:
GOTO label; where
"label has previously been defined in a label declaration statement.
For
The label may not lie out qf the current pracedure or fuflction block.
example:
S
.
Page 9—3
STATEMENTS
(*6+)
PROGRAM Tip;
VAR
—
Cost, Percent, Tip
:
REAL;
Query
:
CHAR;
LABEL 100;
BEGIN. .(Program Tip)
WRITELN('Let''S calculate the waiter''s
WRITEYWaS it good service (Y or
N)?:
'); tip');
READLN (Query);
IF Query = 'N' THEN 6010
100;
WRITE('How much did you pay for
dinner? ');
READLN(Cost);
WRITE('What pe:rcentage do you want to
READLN(Percent);
Percent *= 0.01;
Tip
Percent * Cost;
WRITELN('The tip is: ',Tip);
END (Program Tip).
tip? ');
100:
NOTE:
The
AlphaPascalcompiler is initially set so that recognize GOTO statements; that is, It gives the error message it does not
"Illegal.
symbol." compiler
if it
encounters a
6010 statement in your program.
compiler that you want to use 6010 statements option
$G+ must appear at the
in a particular
fropt of information on the $6 compiler option, see
Section
Options (*6+ and $6—).")
To tell the
program, that program.
the
(For
4.3.2.1,
"The
6010
9.5
NULL STATEMENT
One of the features that make Pascal programs especially
flexible is the
fact that you may include a null statement within your programs.
A null statement allows you to include extra semicolons within compound statements, and to omit statements in certain program constructs.
For example, consider the CASE expression below:
CASE expression OF
I
: statementi;
2
: statement2;
3
:
4
:
; statement3;
ELSE statement4
C Null statement )
By including just a semicolon after value 3, we tell the CASE perform no statement if the expression evaluates to 3.
expression to
Page 9—4
STATEMENT'S
As another example:
IF A =
B THEN
—
IF
C =
D
THEN Flag
:
TRUE
{ Null statement after ELSE )
ELSE
NewFlag
:
True;
ELSE the first IF—THEN construct.
ELSE to
The use of the null statement above aLlows us to attach the second
(Otherwise, the second else woutd be performed when C <>
0, rather than when A <> B.)
9.6
COMPOUND STATEMENT
The body of a Pascal program is a compound statement; that is, It is marked with the BEGIN and END keywords, and contains one or more statements between those keywords (even if the enclosed statement(s) is a nutt statement—— see the paragraph above, Section 9.5, "The Null
Statement").
Each individual statement may also consist of a compound statement.
The use of compound statements is what structure.
gives a Pascal program its nested, block
Many sample programs In this book contain severaL
BEGIN—END blocks.
(See Section
6.2, "LabeL
DecLarations," for information on labeling
BEGIN—END keyword pairs.
Labeling these keywords tells the compiler to
BEGIN—END keywords are not report back to you with an error messageif the matched as your Labels have indicated they should be.)
9.7
CONDITIONAL STATEMENTS
Conditional statements allow you to execute certain sections of code onLy if specific conditions are satisfied.
This section.
discusses the
IFTHEN,
IF—THEN—ELSE, CASE—OF, and CASE—OF—ELSE statements.
9.7.1
IF—THEN
The IF—THEN statement takes the form:
IF Boolean expression THEN statement; where statement may, of course, consist of a compound statement.
expression is one which evaluates to a BooLean value.
For example: evaluated as FALSE, since I is not greater than 5.
For example:
A Boolean
1>5
Is
IF TestScore )
90
THEN WRITELN('Congratulations! An A+');
Page 9—5
STATEMENTS
The statement(s) expression following evaluates- to the THEN clause are,
TRUE; transferred to the next statement
if it
evaluates after the IF—THEN
carried out If the
Boolean to
FALSE, statement.
control
Is
Note that the statement following statement.
For example: the THEN keyword may itself be an INTHEN
IF Single THEN
IFWlthqJ.diflg > .36 THEN Dependents
:
1;
(Which is the same as:
IF
Single evaluates
Single
AND
(Witholdiag
>
.36) to
TRUE, everything after the executed; otherwise, control passes to the next program
THEN...) statement.
If first
THEN keyword is
NOTE: You may include the keywords IF—THEN in an expression to evaluate one of two alternative
Expressions." expressions.
conditionally
See Section 8.4,
"IF—THEN—ELSE
9.7.1.1
IF—THEN—ELSE — The statement gives us a way addition of an ELSE clause to an
IF—THEN to select one of two statements as evaluating an expression.
The IF—THEN—ELSE statement takes
a result of
the form:
IF Boolean expression THEN statement—I ELSE statement2
If the
Soolean expression is
TRUE, the first statement is executed; otherwise, the second statement is executed.
IF—THEN statement above, a compound single statement.
tatement
As in the case of the simpte may
One of the two statements will appear in place always be executed.
of a
For example:
IF Margin > LineWidth THEN Error
:
PGWDTH ELSE LineWidth —= Margin;
The line above Is from a program that formats documents.
Margin is greater than the current Linewldth, then we
If the
value for set an error code into the Error flag; otherwise, we reset the
LineWidth to the old value minus the
Margin.
What happens if an
IF—THEN—ELSE statement contains statements?
To which IF—THEN statement does the ELSE apply?
multiple
INTHEN
For example:
A = B THEN jf B = C THEN Flag := 0 ELSE Flag
:
1;
Does Flag get set to 1 if A>B or if B>C?
AlphaPascal nests
ELSE5.
means that in the case above, the
ELSE statement; if 8C is FALSE, Flag 'is set to 1.
As another example:
That
applis
to the last IFTHEN
Page 9—6
STATEMENTS
PROGRAM DoubleElse;
VAR
A,B,.C,D
:
REAL;
BEGIN 'C DoubteEtse }
WRITE('Enter A, B, C, D:
READLN(A,B,C,D)
);
'C Enter values for A,B,C,D 1;
IF A = B
THEN IF C = 0
TIEN WRITELN('NO Else')
ELSE WRITELN('Elsel')
ELSE WRITELN('Else2')
END 'C DoubleElse ).
As we said, ELSE5 are nested.
That means that the second ELSE
is applied if the first IF clause (A8) is false; the
first ELSE is applied If the
second
IF clause
(CD) follows: is false.
So, the output from the program above is as
AB
True
False
True
False
CD
True
True
False
False
Output
No Else
ElseZ
Elsel
Else2
9.7.2
CASE—OF
The CASE statement allows you to select one out of a group execution.
The CASE statement takes this form: of statements for
CASE expression OF
Case—label. ..,Case—label
:
Case—label.. .,Case—label
: statementi; statement2;
END
Case—label.. .,Case—tabel
: statementN
The expression (called the "selector") is evaluated, and its value must be the same as one of the case—labels.
A selector must not be of type REAL, and it must be of the same type as the case—labels.
You may have as many case—labels as you like, but each case—label may appear only once In any one
CASE statement.
When a matching case—label following that case—label is executed.
For example: is found, the statement
Page 9—7
STATEMENTS
BEGIN 'C MainMenu )
WRflE('En'ter your choice
READLN (MenuChOi ce);
CASE Menuchoice OF
Computelax
'B'
:
UpdateAceOUnt
'C'
:
PrintReport
'0'
:
DoBilling
END{ End-of CASE);
END 'C MainMenu ).
from the menu above
:');
The program block above performs the proper selection from the main menu.
procedure based on the user
NOTE:
What happens if none of the
Pascal. says that such an event case—labels match the is undefined.
selector? Standard
AAphaPasc&l simply says that control passes to the next
If none of the program statement.
case—labels are matched, then
(See the next paragraph fcr Information on using an ELSE clause to catch a situation where no match occurs.)
9.7.2.1
CASE—OF—ELSE — AIphaPascat. allows a statement; the CASE—OF—ELSE statement.
unique variant to the
CASE
This statement takes the form:
CASE expression OF
Case—label.. .,Case—label
:
Case—label.. .,case—late,l
: statementi; statement2;
S
Case—label...,Casetabet : statementN
ELSE statement;
For example:
BEGIN 'C MainMenu )
WRITE('Enter your choice: ');
READLN (MenuChoi ce);
CASE MenuChoice OF
'A'
:
ComputeTax;
'B'
:
Update-Account;
'C'
PrintReport;
DoBilling
ELSE WRITELN('No valid choice')
END C MainMenu ).
'C Didn't enter A,B,C, or 0
Notice keyword.
that the ELSE clause takes the place of the final CASE statement END
NOTE: See Section 8.5,
"CASE
Expressions," for information on using construct to conditionally evaluate one of several alternative the CASE expressions.
Page 9—8
STATEMENTS
9.8
REPETITIVE STATEMENTS
It is often the case that one section of a program must be performed on a certain condition.
AtphaPascal provides a number repetitively, based
REPEAT—UNTIL, and
FOR—DO.
It is of repetitive statements:
WHILE—DO, important that you decide which of these statements Is exactly correct for your application, since each differs somewhat in the way that it handles final values.
9.8.1
WHILE—DO
The WHILE—DO statement takes the form:
WHILE Boolean expression DO statement where the Bootean expression evaluates to a TRUE or FALSE, and the statement may consist of a compound statement.
For example:
PROGRAM;
VAR
Counter, Number, Average, Sum
:
REAL;
BEGIN C Main Program }
Number
1
C Initialize Number to >
Average
:
Counter
:
0;
WHILE Number > 0
DO
BEGIN
WRITELN('Average:
Counter i-
1;
',Average);
WRITE('Enter number: ');
READLN (Number);
Sum +
Number;
Average :=
Sum/Counter;
END;
END TWain Program 3.
0.
3
In effect, you tell Pascal, "While the following condition is TRUE, execute the following statements."
As soon as the condition becomes
FALSE, the program finishes executing the entire WHILE loop, and then goes on to the next program statement.
It is possible that a
WHILE loop will never be executed if the initial condition is not true and never becomes true.
9.8.2
REPEAT—UNTIL
The REPEAT—UNTIL statement takes this form:
REPEAT statement—list UNTIL Boolean expression
Page 9—9
STATEMENTS where statement-List may and expression evaluates be seriis of statements to TRUE or FALSE.
separated by semicolons,
For exampLe
PROGRAM,
VAR
Number
:
INTEGER;
Error :
BOOLEAN;
BEGIN C Mai,p. program )
Error :
FALSE;
REPEAT
WRITE('Enter an integer divisible by 3: ');
READLN
IF
(Number);
(Number MOD 3) = 0
THEN
—
WRITELN('Correct.
Try another.') ELSE Error
;
TRUE
UNTIL Error
WRITELN('Incorrect. End of exercise.')
END C Main Program}.
Loop
(making it
(however, you may do so if you beginning, and end of the
Because the REPEAT—UNTIL keywords appar at the do cIear where the beginning and end of the Loop are), we the
REPEAT keyword not have to include the
BEGIN—END keywords after wish).
A REPEAT looP will always be executed at Least once.
9.8.3
FOR—DO
The
FOR—DO statement allows statements a specific number of value of the "control variable" some terminal value.
A you to execute a given statement or group times.
A FOR—DO .tOop is executed for of every from some starting value up to and including control variaIlé must not be of type REM..
The
FOR—DO statement takes this form:
FOR Variable—identifier
: expression ?exPression DO statement
For example:
PROGRAM;
VAR
Counter
:
INTEGER;
BEGIN C Main Program 3
WRITELN('The square roots of the integers
1 to 10 are
WRITELN;
FOR Counter
:
1 TO 10 DO WRITELN('Square root:
END C Main Program 3T
—
',SQRT(Counter))
Each time the statement after the DO incremented by one.
keyword is executed,
Counter is
The program above prints the square roots of the integers from '1 to 10.
Page 9—10
STATEMENTS
A variant of the FOR4O loop exists that allows you to control variable.
It takes the form: decrement the
FOR Variable—identifier
: expression DOWNTO expression DO statement
Each time the statement after the DO keyword is executed, the cottrot variable is decremented by one.
Note that it is possible that a may not be executed at alt, if the initial and
FOR—DO Loop terminaL values of the
(For example, the statement control variable are not in the proper range.
FOR I
:= S TO 1... wilt not be executed, but FOR I
:
5 DOWNTO 1... wilt be executed.)
9.9
WITH—DO
The WITH—DO statement aLlows were simple variables.
you to access fields of a record as If they
The WITH—DO statement takes the form:
WITH Variable_identifier1...,V8riableidentifit
DO statement
The WITH—DO statement simply gives you a shorthand way of accessing record fields without specifying the name of the record structure for each access.
(See Section 7.2.7, "RECORDS,' for information on records.)
For example, suppose you have a record made up of the following fields:
Carlnfo.Model
Carlnfo.Year
Carlnfo.Color
Carlnfo. Seria lNumber
You have 100 cars on your car lot, and you want to know how many of red.
The records may be set up this way: them are
TYPE
Carlnfo = RECORD
Model
:
STRINGC3];
Year
:
INTEGER;
Color
:
$TRING(3];
SerialNumber
INTEGER;
END C record )-;
VAR
Counter,CarNumber
:
INTEGER;
CarLot
ARRAY E1..100] OF Carlnfo;
Now you can process them.
Without using a WITH—DO statement, you would have to do something like this:
Page 9—11
STATEMENTS
Counter :
0;
FOR CarNumbçj'
:
1
TO 100 DO
BEGIN
(CarLotCCarNUmber).M0tXZO')
IF
AND (CarLotuCarNumber]
THEN Counter 4=
1;
.Color' red')
WRITELN('Number of red XZOs is: ',Counter)
A more convenient way"is to use the WITH—DO statement:
Counter
:
0;
FOR CarNumber
:
1
TO 100 DO
BEGIN
WITH CarLotiCarNumber] DO
IF (Modet'XZO') AND
(Color'red') THEN Counter +
WRITELN('Number of reTT2Os ii:
',CountiFY
1;
By specifying more than one access data in the variable—identifier, you can use reàord CarL.ot.MakE.MOdet, you the WITHDO
For example, to statement to access fields that occur within record fields.
could write something like this:
WITH CarLot,Make DO
Model
:
'HatchBack';
This is equivalent to:
WITH CarLot DO
WITH Make DO
Model :i'HatchBack';
.
44
CHAPTER 10
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
The functions and procedures discussed in this chapter are used to transfer data between your programs and the users of those programs, and between programs and
files.
The routines chapter, "Basic Functions and
Procedures,' are routines standard
Pascal wiUl probably be
we describe in the first part of the
chapter,
"Special
Functions and
Procedures descriptions the AMOS file structure.
familiar
with.
that users of
The last part of the for File
I/O," contains of functions and procedures that are particularly for use with
NOTE: You wiLl notice that we use the term "file—identifier" when discussing a file variable, rather than the, simple term "file" (sometimes qsed by other
Pascal books).
This is to help avoid confusing the file—identifier with the
"file specification," which is the specification oi
the actual
AMOS disk
file that is associated with the file variable.
Using an AMOS file requires that you first declare the file—identifier and then associate it with the
file specification of
an
AMOS disk file.
'See
Section
10.2,
"Special
Functions and
Procedures for File I/O," for more information on using AMOS disk files, especially Section 10.2.12, "OPEN.")
10.1
BASIC FUNCTIONS AND PROCEDURES
These are the Input/Output functions and procedures that users of standard
Pascal
will
be most familiar with.
Later sections in this chapter discuss special input/output functions and procedures that allow your programs to access the AMOS file structure.
You will often use the procedures GET, PUT, READ, READLN, WRITE, and WRITELN for transferring data between your program and the users of your program.
These procedures are also used to transfer data between your program and special storage areas called this section, PAGE, RESET, and REWRITE, are used only with files.
Remember that when
"files."
The other procedures discussed in we talk about "files," we are referring to the special data type
FILE that in AlphaPascal can be associated with AMOS disk files.
INPUT/OUTPUT FUNCTIONS AND
PROCEDURES
Page 10—2
Three special pre—dectared of: file—identifiers exist that you should be aware
INPUT
Specifying
INPUT tells
AlphaPascal that you want to use the terminal as an input file.
For example, when you use
READLN to get data from the terminal keyboard:
OUTPUT
READLN (EmptoyeeNumber,Dept); you have implicitly said:
READIN (INPUT,EmployeeNumber,r,ept);
(In other words, if you omit a file—identifier from the arguments given to the READLN procedure, READLN assumes you want to use
INPUT.) INPUT is a TEXT file.
Specifying
OUTPUT tells
AlphaPascal to use the terminal as an output file.
For example, when you write data to the terminal display via the WRITELN procedure:
WRITELN('Enter your Employee Number:
); you have implicitly said:
WRITEU4(OUTPIJT,'Enter your Employee Number: ');
OUTPUT is a TEXT file.
KEYBOARD
The
KEYBOARD file—identifier acts much the same as INPUT, except that if the terminal is in Charmode, the characters typed by the user of your program will not echo on the terminal display.
For example:
CHARMODE;
WRITELN('Enter password: ');
READ(KEYBOARD,password);
Asks the user of your program for a password, but does not display the characters of the password as they are entered.
When your terminal is not in Charmode and you are using INPUT, the monitor processes and filters your input.
(For example, it appends a line—feed to the end of a carriage return.)
KEYBOARD and Charmode give you a way to examine the input exactly as it is entered; the monitor does no processing of the characters.
That means that for the example above to work, after typing the password, the user must file.
type
(For a carriage return AND a line—feed.
information on Charmode, see
KEYBOARD is a TEXT
Section 11.2.1,
"Charmode.")
INPUT,
OUTPUT, and
KEYBOARD are associated with the special AMOS file specifications TTY:, TTY:, and KBD:.
See Section 10.2.1 for information on these special devices.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—5
If
you are using
READ to input data, remember that you wilt have to do a
READLN after end—of—line has been readhed to make It read past the tine—feed at the end of the carriage return in order to reset
EOLN to
FALSE.
For example:
PROGRAM TestEOLN 'C Count how many characters are in input };
VAR
Source
:
CHAR 'C Input.);
CouDter
:
INTEGER;
BEGIN 'C TestEOLN )
WRXTE('Enter a line of characters: ');
READ(Source);
Counter
:
0;
WHILE NOT EOLN DO
BEGIN
WRITE(Source);
Counter += 1;
READ(Source)
END;
WRI't!rN;
WRITELN('—— number of characters = ',Counter);
READLN 'C Restore EOLN )
END 'C TestEOLN ).
The
(that is, until EOLP is TRUE).
the program above input keeps reading characters until the user enters a RETURN
Then it prints the number of characters in string. For example, a sample run of the program might look like
this:
Enter a line of characters: NOW IS THE TIME
NOW IS THE TIME
—— number of characters = 15
10.1.4
GET and PUT
GET and PUT are the two basic file I/O procedures.
You may use GET and
PUT
on files of any type, not just TEXT files.
10.1.4.1
GET —
GET advances the component, buffer variable to the next in doing so, it assigns the value of that file component to buffer variable.
The invocation takes the form: file the
GET(fi It—identifier);
INPUT/OUTPUT FUNCTIONS
AND PROCEDURES
Page
lO6
where fileidentifièr is a fiLe variabLe,
variable past the end of the file,
the
If doing a GET moves the buffer then the EOF function returns contents of the buffer variable is undefined.
access the very last item in the file,
TRUE, and
So, save the contents of the buffer variable into another variable before doing a GET, if you need to
10,1,4,2
PUT
PUT writes the value of the component buffer variable into the
at the current file position,
The procedure invocation takes the form:
PUT(fileidentifier);
where fiLe"identifier is a file variable.
The EOF function remains TRUE,
10,1,4,3
Sample Program
Using
GET and
PUT "
Below is program using GET and PUT, in
Section disk file, NUMBER,DAT,
for input,
a very simple
Notice that we use the OPEN statement (described
10,2,12) to associate the file-'identifier DataFi Ic with an AMOS
The RESET procedure closes the file and re'opens
it
PROGRAM Fi leAccess;
VAR
DataFile
:
FILE OF CHAR;
Entry
:
CHAR;
Counter
:
INTEGER;
BEGIN { Fl leAccess }
"WN(DataFiie/NUMBER,DAT,OUTPUT);
C Open NUMBER,DAT for output }
FOR Counter
:
1
TO 5
DO
BEGIN
WRITEVEnter data: );
READLN(Ent ry);
DataFiie := Entry;
PUT(DataFjle)
C Get data from terminal }
C Assign data to buffer var )
C Write to file }
END;
RESET(DataFi le);
WHILE NOT EOF(DataFi Ic)
DO
C Get data till file is empty }
BEGIN
Entry := DataFile';
WRITELN(Entry);
GET(DataFi Le)
END;
END C Fl LeAccess :i,
C Close file and re-'open for input }
C Get data from file }
NOTE:
If
you use
OPEN to open a fiLe for input, or if you use RESET, the
first tiLe component is placed into the buffer variable for
you,
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 107
1Ol,S
READ, READLN, WRITE, and WRITELN
The READ and
READLN
(discussed above), procedures are
You elaborations of the
GET procedure should use them only for TEXT files and terminal input,
WRITE and WRITELN are elaborations of the
PUT procedure
(also discussed above); they are for use only with TEXT files and terminal output,
Although we say that these procedures are for use with TEXT files, you will notice throughout this book that we have made wide use of them for transferring data between programs and the terminal,
Remember that your terminal is a TEXT file,
Two TEXT files have been pre"declared for use with the terminal: INPUT and OUTPUT, you want to use the fiLe INPUT,
If you omit the file"identifier from
the list of arguments given to READ and READLN, the procedures assume that
No file"identifier in the list of arguments
given to WRITE and WRITELN indicates that you want to use the file OUTPUT,
One
last
note on
these procedures" they convert REAL or INTEGER data to
type CHAR,
For example, when you say:
WRITE(Result); where Result is an INTEGER variable containing the number 12, WRITE displays the characters "12" on your terminal, This is what you want to do when
you "?a'"d''ta
to a terminal, but be careful in using READs and WRITEs on
actual disk files,
Consider performing file operations on a large file of
INTEGER data, form,
It would be very inefficient to handle that data in character since every time you manipulated it, you would have to re"convert it,
It would be far better to use GETs and PUTs rather than READs and WRITEs to handle the numeric data, since GETs and PUTs do no conversion,
10,1,5,1
READ "
The
READ procedure inputs a
list of variables from the terminal or a fiLe,
You should only use READ for TEXT
files,
NOTE: does not read an entire line of data up to a carriage return/line"feed,
READ
Given the file these actions: variable Data, the procedure READ(Data,Character) performs
1,
2,
3.
Scans over and ignores line"feed characters;
Character := Data';
GET(Data);
The procedure invocation takes the form:
READ(fi le"identifier, list"of"variables);
If you omit the file"identifier:
READ (Ii st"of"variahLes);
INPUT/OIJ'rpuT FUNCTIONS AND PROCEDURES
Page
10—8
READ assumes that you want to use the file
INPUT (that is, that you want input from the terminal keyboard).
to
The READ arguments must be separated by commas.
For example:
READ(DataFl le,CustomerlD,CustomerName); where
Datarile is a file variable identifiers.
Or: variable, and CustomerlD and CustomerName are
READ (Linesi ze,Pagesl ze,PageNumber); where Linesize, Pagesize, and PageNumber are varlabtes to be input from the terminal.
NOTE:
If you input more than one variable via the READ or READLN procedure, those values should not be input separated by commas.
For example, given:
READ(A,B,C);
The r!sponse:
123 is legal, but the response:
1,2,3 is not valid.
If you respond with an illegal number (for example, you input an "A" for a variable of type INTEGER), AlphaPascal assigns a zero to that variable, instead of generating an error.
It is the responsibility of your program to check the validity of data input by the READ procedure.
10.1.5.2
READLN —
READLN inputs a list of variables from a file or the terminal keyboard.
You should only use READIN on TEXT files.
It differs from READ in that it reads an entire line of data up to a carriage return/line—feed pair.
Given READLN(Data,Line), where Data is a file variable, READLN performs the following actions:
Line
:
Data';
WHILE NOT EOLN(Data) DO
GET(Data);
GET(Data)
In other words, until we reach the end of the line
(a carriage return/line—feed pair), read data into the variable Line.
The invocation takes the form:
READLN(fi le—ldentifier,list—of—varjables);
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—9
where file—identifier is a file variable associated with the file
you want to read from,
If you-omit the file—identifier:
READLN( list—of—variables);
READLN terminal.
reads from the pre—declared file INPUT; that is, it reads from the
Separate READLN argunents with commas.
10.1.5.3
WRITE — The WRITE procedure writes a list of expressions to a file or a terminal display.
To print a string, encLose it within single
quotation marks.
You must only use WRITE for TEXT files.
WRITE does not write an end—of—line marker (carriage return/line—feed pair) after writing the specified data.
To begin a new line, use the
WRITELN procedure.
The invocation takes the form:
WRITE(fi le—identifier,expression—Iist),; where want to write the data to, and expression—list Is the data to be written.
The
file—identifier
expression list is a file variable associated with the AMOS file you may contain string lAterals, constants, variables of type INTEGER, REAL, CHAR, PACKED
ARRAYC1..n)
OF
CHAR, and STRING.
example:
For
WRITE(NewFi le,'Two INTEGERs followed by STRING: ',INT,12,'IsaString');
If you omit the file—identifier:
WRITE
WRITE(expression— list); assumes you want terminal display).
to write to the pre—declared file OUTPUT (the
10.1.5.4
WRITELN — WRITELN outputs a list of expr!ssions
to a terminal.
To
WRITE in that
marks.
You must only use WRITELN with TEXT
it
file
a string literal, enclqse it within single quotation
files.
WRITELN
differs
writes an end—of—line marker (carriage return/line—feed
pair) after writing the specified data.
The invocation takes the form: or from
WRITELN(fi le—identifier,expression—list); where file—identifier is a file variable, and expression—list is a expressions to be written.
Separate the WRITELNarguments with commas.
you omit the file—identifier: list of
If
WRITELN (expression—I ist);
INPIJT/OIJtplJT FUNCTIONS AND
PROCEDURES
Page
10—10
WRITELN
You may assumes thaf you want to write to
OUTPUT write just a
(the terminal display).
carriage return/tine—feed to a file or terminal, by omitting the expression—list:
WRITELN(file—identifier); or:
WRITELN;
10.1.5.5
Formatting outputting data.
leading spaces.
Output —
AtphaPascal uses certain conventions for
SIRING data and data of type CHAR are displayed with no
Numbers are written differently, depending on whether they are REAL or INTEGER.
AlphaPascal wilt always print REAL and INTEGER numbers In decimal notation if the number is less than 12 digits. (if the number is larger than
12 digits, the number will be printed in scientific notation.)
If the fractional part of a REAL number is greater than 11 digits, that number wilt be printed in scientific notation.
INTEGER numbers are printed as a sequence of digits, possibly preceded by a minus sign.
INTEGER numbers are not printed with a leading space.
REAL numbers are printed with a leading space, unless the number is negative, in which case the minus sign takes up that space.
REAL numbers are accurate to nearly
12 digits.
They are always rounded to 11 digits before being displayed to avoid annoying output such as 4.9999... instead of 5.
Both WRITE and WRITELN allow you to include optional arguments that give additional formatting instructions to AtphaPascat.
The form of these arguments is (for both WRITE and WRITELN):
WRITE(expressionl
:
X
:
Y,expression2
:
X Y ); where X specifies a minimum field width, and
V specifies the number of digits to write after the decimal point.
X and V must both be of type
INTEGER, and may be constants or variables.
If you are not printing a
REAL number, you may not specify the V argument.
The minimum field width specifies the minimum number of spaces in which the number is to be printed.
For example, if you want AtphaPascal to print the number right—justified in a field of ten spaces, use the value 10 for X.
This gives the minimum field in which to print the number; if the number is larger than the specified field
(for example, it is
11 digits),
AlphaPascal will not truncate the number, but will use the necessary number of spaces.
If the number is a REAL number, you may also specify Y, the number of digits to be printed to the right of the decimal point.
(For example, for dollar values, you would probably want to specify 2.)
AlphaPascal rounds the
REAL number to the specified number of places; it does not truncate it.
4.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page
10—11
Although you will probably find the optional formatting arguments to be of most use in printing numbers, you may also print data of type CHAR or STRING specifying a minimum field width.
By combining formatting of numbers and strings, you can construct tables and charts in whlch titles and numbers are neatly lined up.
exampLe.
See the output of the sampLe program below for a simple
Here are some sample outputs (the "V' symbol indicates a blank):
WRITE(1, —1, 1.0,
—1.0);
1-mi—i
WRITE(O.O, 1.0, 100.010, 0.0012, IE1Z, i.1E12, —1.23E—12);
$0$i$i00.01$.0012b1E12$1 .1E12—1 .23E—12
WRITE(O.0:6:2, 1.0:6:2, 100.010:6:2, 0.0012:6:2, —1.23E—12:6:2);
$$0.00$b1 .0O$100.Olab.OOb—0.00
Below we give a sample program that demonstrates both formatted output and the use of files:
INPUT/OUTpuT FUNCTIONS AND
PROCEDURES
Page 10—12
PROGRAM FormItOutput;
VAR
Report
:
FILE OF REAL;
Year,Profit
:
REAL;
I
:
INTEGER
BEGIN C FormatOutput }
OFEN(Report,'YTD.DAT',oUTpIj);
FOR I
:= I TO 5 DO
C Put data In fiLe. 3
BEGIN C Loop 3
WRITE('Enter Year: ');READLN(Year);
Report:=Year;
PUT(Report);
WRITE('Enter Profit: l);REA:OLN(profjt);
Report :*rofit;
PUT(Report)
END C Loop 3;
RESET(Report);
WRITELN('Year': 6 ,'Profit'
:
WRITELN('
WRITELN;
C Open file again—— for input 3
18 );
C Print header 3
WHILE NOT EOF(Report) DO erGrFrC While—loop V
Year
:
Report;
GET(Report);
Profit := Report;
GET (Report);
WRITELN(Year
: 6,Proflt
:
20
END C While—Loop 3;
'C Print contents untiL End of fiLe)
:
2);
C Format output 3-
END C FormatOutput 3.
The program above prints a neat table of the form:
Year
Profit
1971
1973
1975
1977
1979
650000.56
1205600.34
1865030.89
100450677.34
82380000.90
.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—13
10,1,6
PAGE
The Page procedure writes a form—feed to the specified file,
The invocation takes this form:
PAGE(fi le"identifier)
where file—identifier is a file variable.
10,1,7
RESET
The
RESET procedure
"rewinds' your file to the beginning,
In effect, it
performs a CLOSE and then OPENs the file for input,
The invocation takes the form:
RESET(fi Ic—identifier); where
file—identifier
is the buffer variable for you.
a file variable that is associated with the file
you want to reset,
As does OPEN, RESET inputs the first file component into
10,1,8
REWRITE
The REWRITE procedure opens a file for output,
In
CLOSE followed by an ERASE; then invocation takes the form:
effect,
it
performs a
it
opens the
file for output,
The
REWRITE(fi Ic—identifier); where file—identifier is you want
a file variable that is associated
with the file to rewrite,
REWRITE has the ability to generate file names if no
file specification is associated with the specified file—identifier,
These file names begin with TEMPAA,TMP, and go on to TEMPAB,TMP, TEMPAC,TMP,
TEMPZZ,TMP,
For example, the program:
PROGRAM TestRewrite;
VAR
NewFile
:
FILE OF CHAR;
BEGIN { Testkewrite }
REWRITE(NewFile)
PFILE(NewFile)
END C TestRewrite 3',
No file specification associated with
NewFile 3';
C Print filespec now associated with NewFile 3' prints:
TEMPAA,TMP
INPUT/Output FUNCTIONS AND
PROCEDURES
Page
10—14
10.2
SPECIAL FUNCTIONS AND PROCEDURES
FOR FILE I/O
Standard
Iascal gives about these routines you several functions and procedures that allow you to read and write data from a file (e.g., GET, PUT, in
READ, etc.).
We talked transfer data between the sections above.
Although you will often use most of the functions and procedures discussed in those earlier sectiorn to the terminal and your programs, Alphapascal also provides a number of additional functions and procedures that allow you to work with AMOS disk files.
Using the functions and procedures we discuss below, you can search for, define, open and close sequential and random AMOS files.
The functions and procedures we discuss in the following sections are,:
LOOKIJP
OPEN
OPENI
OPENO
OPENR
CLOSE
FSPEC
EXTENSION
GETFILE
SEflILE
CREATE
SEEK
Searches for specified file; returns Boolean value.
Opens file In input, output, or random mode.
Opens file In Input mode.
Opens file in output mode.
Opens file in random mode.
Closes file associated with specified file—Identifier.
Returns number of charactei's in filespec; associates filespec with file—identifier.
Forces specified extension into file specification.
Reads information in file specification.
Places information into file specification.
Allocates random file blocks
Positions random file to specified file record.
ERASE
FILESIZE
JOBDEV
JOBUSER flILE
RADSO
RENAME
Erases specified file from disk.
Returns number of disk blocks used by file.
Returns device user is logged into.
Returns account user Is logged into.
Prints name of file associated with specified channel
Converts three—character string to RADSO format.
Renames specified file.
10.2.1
Information on AMOS Files
The
AMOS file sequential.
system recognizes two major types files differs somewhat, so of files: random and
Creating, opening, and performing I/O for the two types of
It is important to understand the differences between them.
Before we discuss AMOS disk files, we would like to mention again that the pre—declared file—identifiers
INPUT,
OUTPUT, and KEYBOARD have associated with them special AMOS file specifications: TTY:, TTY:, and KBD:.
TTY: specifies your terminal.
specification to the compiler
(For example, If you give TTY: as the file listing option, $L, the compiler sends the listing to your terminal display.)
The KBD: specification is equivalent to the
TTY: specification except that it prevents input from being echoed to
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—15 the terminal display if the terminat is in Charmode.
(See
Section
11.2.1,
'Charmode," for information on charmode.)
NOTE: monitor appends a line—feed character onto the end of a carriage return.
you
The normal end—of—line separator is a carriage return.
Normally, the are in
Charmode and are using the KBD: device, automatically append a line—feed onto the end Of a carriage
If the monitor does not return.
Therefore, If you are using KDD: in Charmode you should use GETs and PUTs to retrieve data, since. READ has a one—character lokahead buffer which wilt cause it to wait on the tine—feed when it encounters a carriage return.
10.2.1.1
Random Files — Random file blocks are the disk, and access to allocated contiguously on such a file Is random; that is, by computing an offset, the system can access any one record in that file without accessing any other record.
Random file blocks are 512 bytes.
To create a random file, you will use the CREATE procedure.
One advantage in using a random file is that access to that efficient; using the SEEK procedure, you may randomly position to any record in that file without stepping through prior records.
file is very file is the only file which you may read from and write to without ctosing and opening It again.
In addition, a random
Do not use READ and WRITE to get data from a random file; use GETs and PUTs.
You should be aware that the order in which you do GET and PUT procedures makes a difference.
If you do a GET, and then a PUT: to update information in a random file, the Last record retrieved via aET will be updated; do a PUT, and then do a GET, you will get the record after the one you just updated.
A series of GETs will retrieve successive records in a random file
just as it wilt
a sequential successive records.
file.
A series of
PUTs
will
if write you to
The
EOF function does not return TRUE after the end of a random file has been reached; instead, an error is generated.
This error
wilt
also be generated if you SEEK a record beyond the end of the file and then attempt a
GET or PUT.
10.2.1.2
Sequential Files —
Sequential file blocks are allocated in a
linked list on the surface of the disk, with one word at the front
of each block containing the disk address of the next block in the file.
Access to such a file is sequential, since the system has to read each block in order to find out where a specific block is on the disk.
file has been reached.
Sequential file blocks are 510 bytes.
The EOF function returns TRUE after the end of a sequential
INPUT/OUTPUT FUNCTIONS AND
PROCEDURES
Page 10—16
10,2,1,3
Logical
Records one or more '!iogical records, your programs,
CustomerName,
30
Within each disk block of
The size of a logical record is determined by
For example, if a grouping of data bytes;
bytes, your tile logical
blocking logical records into disk bLocks, in a file, you can have your
CustomerAddress, 50 bytes; and, data
file
is
SocialSecurity, 9 records might be 89 bytes,
(For information see Section 12,2,3, "CREATE,") on
A random
file
record may not be larger than 512 file size is 65535 records,
A sequentiaL
file
bytes, and maximum random logical block boundaries, and so may be Larger than 512 bytes, record can cross
10,2,1,4
Opening open i n g and usi and
Setting
Up Files
The usual sequence of events for
a file g6'es this way'"
1,
Declare a file variable,
For example:
2.
VAR
DataFi Ic
:
FILE OF CHAR;
This variable establishes the
tile
channel; the communication line over which your program will transfer data in and file associated with that channel,
In our discussions below, the term
"ti Ic—identifier" refers to the file variable
the actual AMOS file, out of the associated with
Before you can use an
AMOS specification of that
file
file, with declared, and you must open the file, you the have to associate
file—identifier
the you have
This tells
AMOS what
AMOS
file you will be accessing via the file—identifier,
An AMOS file specification consists of:
Device Unit Filename Extension Project—number
Programmer—number
For example:
DSKO: CUSTID, DATC1 00,3] where DSK is the Device, 0 is the Unit, CUSTID is the Filename, DAT is the
Extension,
100 is the Project—number,
Programmer—number, and
3 is the
You can use several procedures to associate the
file specification with the file—identifier
(e,g,, FSPEC,
SETFILE,
EXTENSION),
You can then use
OPENI, OPENO, OPENR, RESET, or
REWRITE to open the file,
Or, you can combine these two steps by using OPEN, which takes the form:
OPEN(file—identifier, filespec, mode); where fi Ic—identifier is a
file
variable; fi lespec is the file
specification in string literal
or variable form, and mode
(INPUT,
OUTPUT, or
RANDOM) tells AlphaPascal whether the file is going to be used for input, output, or (in the case of random files), random
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—17
3.
4.
update.
With INPUT and
RANDOM modes, besides
file—identifier
with a
first record of the file for you.
associating the file specification, OPEN also tnputs the
Once you have set a file up to start doing I/O, you can use
GETs and
PUTS or READs and WRITEs to transfer data between your program
and the file.
The final stage in using an AMOS file: is to close
CLO$E procedure.
Closing the file makes sure that the last record
updated in the file gets written out to the
file, it, and using makes the the file available for being opened again.
(You can't open an open
file.) It also makes the file—identifier available for
association with a possibly
different
AMOS file.
Files are automatically closed when you leave the procedure in which they were declared.
A simple case of opening and reading a file might look something like this:
PROGRAM TestFile;
VAR
CustID
FILE OF STRING 'C Declare file—identifier };
Userrile
:
STRING;
BEGIN 'C TestFite }
WRITE('Ptease enter name of your data file: ');
READLN(Userri le);
OPEN(CustID,UserFile,INPUT)
WRITE(CustID)
CLOSE(CustID)
END C TestFite 3.
'C Open the file; get the data );
'C Display data in buffer 3;
C Close the file 3-
The small program above asks the user for a that file.
file specification and opens
The actual process of using the OPEN procedure inputs the first record of that file into the buffer variable automatically assigned to the
file—identifier, CustID.
10.2.2
CLOSE
You will use the CLOSE procedure to close a sequential file that is opin for output.
Closing the file ensures that the last record will get written to
the file; it also enters the file into the disk directory.
You may not OPEN a file that is already open, so if you have been using a
sequential file for output, and you want to use it for input, you must first
close it and then re—open it for input.
The invocation takes the form:
CLOSE(fl le—identifler); wflere file—identifier is the file variable associated with the AMOS file you want to close.
For example, given:
INPUT/OUTpIfl
FUNCTIONS
AND PROCEDURES
Page 10—18
VAR
TaxRbcs :
FILE OF CHAR; once we have opened and used the AMOS file close it: associated with TaxRecs, we must
CLOSE (TaxRecs);
As your program leaves each procedure or function, those routines are .automaticatly closed for you.
any files declared in
However, using the CLOSE procedure ensures that if you are forced to do a hasty and untidy exit from your program (for example, if a system error occurs), the last record of the file wilt be written when the CLOSE procedure is executed.
Closing a fite also makes its file—identifier available for use with another file.
10.2.3
CREATE
Alt random files must be pre—allocated on the disk before you can use them.
(That means that their maximum size must be established before you use them.
You can copy rando files to sequential files and vice versa, so if you are in doubt about the ultimate size of a file that you are building, good idea it Is a to write the data to a sequential file first, then copy the file to a random file after you know how many records have to be copied.)
The CREATE procedure allocates a random file.
form:
The invocation takes the
CREATE(fi le—identifier,sThi); where file—identifier is a file variable associated with the AMOS file you want to create, and size Is a variable of type INTEGER that designates the number of disk blocks you want the file to contala.
NOTE: You must associate an AMOS file specification with the file—Identifier before using CREATE.
(You may use FSPEC, SEflILE, or OPEN (with the RANDOM mode) to do so.) For example:
PROGRAM RandomFi le;
VAR Ranrile
:
FILE OF STRING;
Counter
:
INTEGER;
BEGIN C RandomFile 3
Counter
:
FSPEC(RanFile,'NEWFIL','DAT');
CREATE(RanFi le,20)
END 'C Randomrite 3.
The program above creates the 20—block random file
NEWFIL..DAT.
The
FSPEC function assigns the filespec NEWFIL.DAT to the file variable FILE RanFile.
NOTE:
CREATE causes an error If the file you are creating already exists or if there are not enough contiguous blocks available for it to be allocated
S
INPUT/OUTpUT FUNCTIONS AND PROCEDURES
Page 10—19 on the disk.
If you wish to create a random file capable of holding X records of type 1, then the number of blocks it wilt require is:
1
+ X
DIV (512 DIV SIZEOF(T))
10.2.4
ERASE
The ERASE procedure erases a tile from the disk.
The invocation takes the form:
ERASE(fj Ic—identifier); where tile—identifier is the tiLe variable associated with the AMOS file you want to erase.
ERASE does not return an error if the specified file is not there.
This makes it very useful for ensuring that the creat+onof new files will be successfully carried out.
For example, since CREATE (see above) and OPENO return an error if the file you want to create already exists, you can use
ERASE before using OPENO or CREATE to make sure that the file you want to open does not already exist.
If the file doesn't exist, ERASE can't erase it, but no error is generated and no harm is done.
If the file does exist,
ERASE erases it, and leaves the way clear for OPENO and CREATE.
We've rewritten the small program in Sectton 10.2.3, "CREATE," to include the ERASE procedure:
PROGRAM TestErase;
VAR RanFile
:
FILE OF CHAR;
Counter
:
INTEGER;
BEGIN C TestErase )
Counter
:
FSPEC(RanFi le,'NEWFLL','DAT');
ERASE(RanFile);
'C Make sure file doesn't already exist )
CREATE
(RanFi le,20)
END C TestErase ).
10.2.5
EXTENSION
The of
EXTENSION procedure forces the specifi:ed extension in the specification the AMOS file associated with the specified file variable.
The invocation takes the form:
EXTENSION(fi le—identifler,,ext);
INPUT/OpjyptJT FUNCTIONS
AND PROCEDURES
Page 10—20 where
file—identifier
and ext is a strlngtiterat
want to force to the file
is the file variable associated specification.
For example: with the AMOS file, or variable that designates the extension you
PROGRAM TestExtension;
VAR
ThePite
:
FILE OF CHAR;
Counter
:
INTEGER;
BEGIN 'C TestExtension }
Counter
:
FSPEC(TheFi le,'NEWFIL','DAT');
EXTENSION(TheFi te,'LST');
PFILE(TheFj Ic)
END 'C TestExtenstion ).
The program above file—identifier TheFile.
Then it uses the EXTENSION procedure to change the extension from DAT to LST.
the
AMOS file associates the
AMOS specification.)
NOTE: file
EXTENSION
NEWFIL.DAT
does with
(Notice the use of the PFILE procedure to the
not change the
extension of the file on the disk, it only
changes the extension of the
file specification associatecfVffh the file—identifier.
10.2.6
FILESIZE file associated with the specifie4, file variable.
used the OPEN or LOOKUP procedure the form:
You must have prevIously on the AMOSf1le.
The invocation takes
FILESIZE(fi Ic—identifier);
where file—identifier is a file variable.
For example:
PROGRAM Testfi leSize;
VAR
Thefile
:
FILE OF CHAR;
Counter
: INTEGER;
BEGIN 'C TestFile$ize )
Counter
:
FSPEC(Theri le,'BIGFIL','DAT');
CREATE (TheM te,50);
WRITELN(The number of disk blocks is: 5FILESIZE(TheFil,e))
END 'C TestFjle5ize ).
First the program above creates the random file BIGFIL.DAT, then it prints:
The number of disk blocks is: SO
.
S
INPUT/OUTPUT FUNCTIONS AND PROCEDURES Page 10—21
10.2.7
ESPEC
The
FSPEC lunction performs two main functions: It associates the specified file variabLe with the specified AMOS file, and It returns the number of
characters in the specified variable or string literal that make up the file
specification part.
The invocation takes the form:
FSPEC(fi Ic—identifier, filename, default—extension); where
file—identifier
the
AMOS is a file variable with which you want to associate filespec, filename gives the name default—extension gives the extension supplied.
For example:
of, the
AMOS file, and you want to use if no extension is
PROGRAM TestFspec;
VAR
Datarile
:
FILE OF CHAR;
UserFite :
STRING,
Counter
: INTEGER;
BEGIN 'C TestFspec )
WRITE('Please enter file specificaton: ');
READLN(UserFl Ic);
Counter
:
FSPEC(DataFile,UserFile,'DAT');
WRITELN('Number of characters: ',Counter);
WRITE('File spec is:
');
PFILE(DataFi Ic)
END 'C TestFspec 3.
You can use FSPEC to input an entire command specification.
If the user of the program enters:
line,
not just a file
NEW,OLD the program prints:
Number of characters: 3
File spec is: NEW.DAT
Then we can use the DELETE procedure:
DELETE (UserFi le,1,Counter) to Leave the remainder of the user input ('OLD') in Userrile.
(Note that we used PFILE to print the name of the file associated with the file variable DataFile, and that the
FSPEC function added the default extension of .DAT.)
*
INPLJT/OUVPJT FUNCTIONS
AND PROCEDURES
Page 10—22
10.2.8
GETFILE
The is form:
GETFILE procedure allows you to find out exactly what file specification associated with a specific file—identifier.
The invocation takes the
GETFILE(file—identifier, 0ev, Unit,
Fuel, Fite2, Ext, Proj, Prog);
The arguments are declared INTEGER integers, because file variables.
The data is returned as specifications are stored internally by AMOS in a special numeric form called 'RADSO." RADSO format compresses thr!e bytes of
ASCII data into two bytes of numeric data.
the file and second three*RAD5Q characters
(In other words, GETFILE returns specification In RAD5O form.) Fuel and FiteZ are the first three of the filename.
Although GETFILE may not sound too useful by itself, by more than one file you doing
GETFILEs on can compare elements of the specifications for those files, and by using SETFILE (described in Settlon 10.2.20, below), you can actually change those elements.
For example, consider the program below.
It asks for the specifications of two files do two data files needed for input; if those not exist on the same device and untt, the program moves the files to the System Device, 051(0:, so that they are Oh the same disk device and unit.
.
C
.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—23
PROGRAM;
TYPE
Datafi Ic = FILE. OF CHAR;
VAR
Dev, Unit, F1LeA, Files, Ext, Proj, Prog: INTEGER;
Devi, Uniti, FiteAl, FiteBi, Exti, Proji, Progi
:
INTEGER;
MaitLabel, Addresses
:
Datarile
BEGIN 'C Main Program 3'
WRITELN('Enter the specifications of your two data files');
WRITELN;
WRITE('File #1: ');READLN(Userspec);
WRITE('File #2: ');READLN(Userspecl);
OPEN(MailLabet,Userspec,OijTpUT); C Open the user —specified fiLes 3
OPEN (Addresses,user$pecl ,OUTPUT);
GETFILE(Mai lLabet,Dev,Unit,Fi leA,Fi LeB,Ext,Proj,Prog);
GETFILE(Addresses,Devl,Unitl,Fj leAl,Fi leBi,Exti,.Projl,Progl);
C See If files are on the same disk 3'
IF (Dcv C> Dcvi) OR (Unit <> Uniti) THEN.
BEGIN
WRITE('You have asked for files: '); PFLLE(Userspec);
WRITE(' and '); PFILE(Userspecl); WRITELN; WRLTELN;
WRITELN('Both of your data files must be on the same');
WRITELN('device and unit; we are moving them both to DSKO:.');
SETFILE(Mai lLabel,RAD5O('DSK'),RADSO('O'),Fi teA,Fl teB,Ext,Proj,Prog);
SETFILE(Addresses,RAD5O('D$K'),RADSO('Q'),Fl LeAl,FI teal,
Extl,Proji,Progl)
a;
WRITE('Your files are: ');PFILE(Userspec);
WRITE(' and ');PFILE(Userspeci);
END C Main Program 3.
10.2.9
JOBDEV
The
JOBDEV function takes two INTEGER variable arguments.
The invocation takes the form:
JOBDEV(Dev,Uni t);
JOBDEV returns In Dcv the device you are currently logged into (in
RADSO form), and returns in Unit the device unit you are currently Logged into (In
INTEGER form).
INPUT/QUTPtJT FUNCTIONS AND
PROCEDURES
Page 10—24
10.2.10
JOBUSER
The
JOBUSER takes the form: functi,n takes two INTEGER variabLe arguments.
JOBUSER (Proj ect,Programmer);
The invocation
It returns in Project the project number and
(in decimal) you are logged into, returns in Programmer the programmer number (in decimal) you are logged into.
10.2.11
LOOKUP
The LOOKUP function returns a TRUE or a
FALSE depending on whether the specified file exists.
The Invocation takes the form:
LOOKUP(fi le—identifler); where fite—identifier is the file variable associated with the AMOS file you are looking for.
Since several file procedures generate an error if the file specified to them already exists (e.g.,
OPENO, CREATE), white other procedures generate an error if the file doesn't exist, doing a LOOKUP before one of these procedures is a good idea.
For example:
PROGRAM LookForlt;
VAR FILeID
:
FILE
Of CHAR;
Target
:
STRING;
Query
:
CHAR;
X
INTEGER;
BEGIN C LookFortt }
WRITE('Enter the file you want to write to:
'); READLN(Target);
X
:
FSPEC(FiteID,Target,'DAT');
IF LOOKUP(FiteID)
THEN
BEGIN
WRITE('That file already exists. Destroy it? Ct or N): ');
READLN
(Query);
IF Query =
'N'
THEN EXIT(PROGRAM);
ERASE(Fi LeID);
WRITELN('Fite erased.')
OPENO(Fi leID);
WRITELN('Fite ',Target,' opened for output.)
END
C LookForlt
3.
The program above checks to see if the tile specified by the user already exists.
If the file exists, the user is asked to decide whether or not to save the file, or get rid of It and start a new one of that name.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—25
10.2.12
OPEN
The OPEN procedure opens a sequential file for :snput or output, or opens a random file for both input and output.
The invocation takes the form:
OPEN (file—identifier, filespec, mode); where file—identifier is a file variable, and filespec is a valid AMOS file specification.
Mode may be INPUT, OUTPUT, or RANDOM, and specifies whether the file is to be a sequential file used for input or output, or (in the case of RANDOM), whether it is to be a random file used for input and output both.
If you are using OPEN in. OUTPUT mode, it deletes the specified file if it already exists.
Default extension is .DAT.
For example:
OPEN (INP, 'TEST', RANDOM); associates the AMOS file TEST.DAT with the file—identifier INP, and opens the random file for input and output.
Most of the sampLe programs in this chapter use the OPEN procedure.
NOTE: OPEN variable.
in INPUT or RANDOM mode inputs the first record into the buffer
10.2.13
OPENI
OPENI is a variation of the OPEN procedure; It opens a sequential file for input.
The invocation takes the form:
OPENI(fi Ic—identifier); where file—identifier Is a file variable associatethwith the AMOS file you want to open.
If the file does not exist or if the fiteidentifier has not been associated with an AMOS file (via an ESPEC or SETFILE) OPENI generates an error.
OPENI inputs the first record of the file into the buffer variable.
10.2.14
OPENO
OPENO is output.
a variation of the OPEN procedure; it opens a seAuential file for
The invocation takes the form:
OPENO(fi Ic—identifier); where file—Identifier is the file variable associated with the AMOS file you want to open.
If the file already exists or if the file—identifier has not been associated with an AMOS file (via FSPEC or SETFILE), OPENO generates an error.
INPUT/OUTPUT FUNCTIONS
AND PROCEDURES
Page 10—26
10.2.15
OPENR
OPENR is a variatton-of and output.
The
file
the OPEN proâedure; invocation takes the form: must
exist,
and it opens a random may
file for input
not already be open.
The
OPENR(fj le—identifier); where f1te—idntjfjer want to open.
is the file variable
associated with the AMOS file you
NOTE: OPENR inputs
the first record of the
file into the buffer variable.
10.2.16
PERt
The PFILE procedure associated with the form: displays on your terminal the specified
AMOS file specification
file—identifier.
The Invocation takes the
PFftE(fi Ic—identifier); where file—identifier is a file variable associated with the AMOS file specification you want to see.
(Several of the chapter use PFILE.) sample programs in whose this
10.2.17
RADSO
The
AMOS system stoces much of special form, called "RADSO." into two bytes of numeric data.
RADSO form.
This necessary procedure, since
SETFILE
For example, if you is
AMOS file specification, the information used by the file
RADSO compresses three bytes
The RAD5O procedure converts expects if you are going to
a string into
use the
SETFILE several of its arguments in RAD5O form.
are planning to use SETFILE to change the system in a of
ASCII data filename of an you wilt do a GETFILE to get that specification:
GETFILE(Theri le,Dev,Unit,pi lnaml,Fi lnam2,Ext,Proj,Prog);
The elements 0ev, Filnaml, Filenam2, and Ext are returned
Now, you will do a SETFILE to change the Filename: in
RADSO form.
SETFILE(TheFj leFDevUnit;RAD5O(sNEws)
RADSO('NAM1) Ext Proj prog); leaving the rest of the elements as they were.
.
S
INPUT/OUTPUT FUNCTIONS AND PROCEDURES Page 10—27
10.2.18
RENAME
The RENAME? procedure takes the form: auows you to rename an AMOS tilt.
The invocation
RENAME(f I le—identifier,newname);, where file—identifier is a file variable assoctated with the AMOS want to example, if the AMOS fiLe CURRNT.DAT is associated with the
Accountsri Ic: file rename, and newname is a string variable or a string literal.
you
For
tile—identifier
RENAME(AccountsFi Ie,'BACKUP.LST'); renames supply to RENAME, you can rename just the extension, just the filename, or both.
the
AMOS file CURRNT.DAT to BACKUP.LST.
For example, tile—identifier MailBox: if the
By varying the fields you
AMOS tile OLDDAT.DAT is associated with the
RENAME(Mai IBox,' .BAK'); renames OLDDAT.DAT to OLDDAT.BAK, and
RENAME(Mai IBox, 'ARCHly'); renames OLDDAT.,DAT to ARCHIV.DAT.
10.2.19
SEEK
The SEEK procedure allows you to position a file pointer to a
record in a random file for file I/O.
The invocation takes the form: specific
SEEK(fi le—identifier,recordnu&; where file—identifier is a file variable associated with the random file we want to access, and recordnum is an integer specifies the number of the record to access.
variable or constant that
(The first record is record
#0.)
REMEMBER: SEEK does not input a record into the
positions the tile pointer.
buffer variable;
it
just
10.2.20
SETFILE
SETFILE takes the same arguments as GETFILE, but it puts information into
the file specification.
It also associates the specified
file—Identifier
with the specified AMOS file.
The invocation takes the form:
SETFILE(fite—ldentlfier, Dcv, Unit, Filel, File2, Ext, Proj, Prog);
INPUT/OLJTpIJT FUNCTIONS
AND PROCEDURES
Page lO-'28
For exampLe:
SETFILE(NeH La 00 Fl
F2 RADSO( LSTa) 0 O)
The sampLe above is changing the extensi
NewFiie
to LST,
programmer number teLls AMOS number device
AND specification device
(the account you are Logged into),
(eg, the
NOTE:
unit
Specifying a zero
RAD5OVD5Kfl), you
specifying a negative 1
number
for the unit,
of SETFILE, see Section 1O,28, to use the
(the device and unit
forces you on of the AMOS fiLe associated with for both the project
AND the current defauLt proj ect"prog rammer
Specifying a zero for both the
AMOS to use the defauLt device are Logged into),
If you specify can teLL AMOS to use the default unit, by
For a more Lengthy exampLe of the
"GETFILE" use a
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—29
103
SAMPLE PROGRAM TO DEMONSTRATE FILE HANDLING
The program: he Low maintained is an example of a programming solution to a business and problem: maintaining empl
file
number change, techniques to the need maintain
for an efficient way of reading in, oyee information,
Our sample program below the following of employees: name, age, and in alphabetical order by name
List, or display
employee records, information for a sex.
The employee of employee.
You may very common organi z i ng, uses random user"deffned records are add, delete,
10,3,1
Sample Run
A sample run looks like this (We will underline the information that the user of the program types in):
PRUN DEMO Jfl
C The screen clears >
AlphaPascal Random File Demonstration
Do you wish to (re'Dcreate employee file? y
How many records to you wish to use? 20
C The screen
clears >
Enter option EA)dd, C)hange,
Last Name = ZUCKER RET
First Name = SUE ELLEN
Middle Initial
=
How old is SUE ELLEN? 23
Is SUE ELLEN male? Y
D)eiete, I)nquire, L)ist, Q)uitj:
Enter option LA)dd, C)hange,
Last Name = ARROWSMITH JO
First Name
Middle 1nitiaL=C
How old is JACK? 51
Is JACK male? Y
D)elete,
I)nquire,
L)ist, Q)uitj: ACED
Enter option CA)dd, C)hange, D)elete, I)nquire, L)ist, Q)uit]: A
Last Name = ALLEN
First Name
Middle Initial
How
Is
EDNA male?
EDNA
N
INPUT/OUu'y FUNCTIONS
AND PROCEDURES
Enter option CA)dcj,
C)hange, D)etete, I)nqujre,
1)1st, Q)ult]: L@!
ALLEN, EDNA N: 35 years
ARROWSMITH, JACK C; 51
ZUCKER, SUE ELLEN R: 23 old, sex: female years old, sex: male years old, sex: mate
Total of 3 employee(s)
Enter option CA)dd, C)hange,
Last
Name = ZUCKER
First Name =
@
SUU[LLENffi
Middle Initial =
R liED
How old Is SUE ELaN? 23 JD
Is
SUE ELLEN male? !th
D)etete, E)nqulr,, L)lst, Cult);
C@D
Enter option (A)dd, C)hange, D)elete,
I)nqulre, L)ist, Q)ult): L!±D
ALLEN, EDNA N: 35 years old, sex: female
ARROWSMITH, JACK C: 51 years old, sex: mate
ZUCKER, SUE ELLEN R: 23 years old, sex; female
Enter option EA)dd, *C)hange, D)elete,
I)nqulre, 1)1st, Q)uit): !lE
Page 10—30
< The screen clears >
Leaving AlphaPascat Random File Demonstration
.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—31
10.3.2
The Program
PROGRAM Empl.oyeeMaintenance;
TYPE
-
NameRecord
=
RECORD
First: STRINGEI1];
Middle: CHAR;
Last: STRINGCI5];
END CNameRecord) ;
(Control,Data,Unused);
EmpRecord = RECORD
CASE EmpRecType OF
EmpRecType
Data:
C
Name: NameRecord;
Age: INTEGER;
Sex: (Mate, Female);.
NextDataRecord: INtEGER);
Control:
C
FirstDataRecord: ARRAY C'A'.'Z') OF INTEGER;
Fi rstUnusedRecord: INTEGER);
Unused:
C
NextUnusedRecord: INTEGER);
END CEmpRecord) ;
EmpFileType =
FILE
OF EmpRecord;
(Global Variables)
VAR
EmpFile: EmpFiteType;
RecNum, PreviousRecNum: INTEGER;
ControtRecord: EmpRecord:
FUNCTION SameNames(Namel ,Name2: NameRecord): BOOLEAN;
(Returns TRUE if Namel =
Name2)
BEGIN
SameNames
:
(t4amei.First
=
AND (Namel.Middle =
AND (Namel.Last =
Name2-.First)
Name2.Middte)
Name2.Last)
END (SameNames) ;
(Changed 30 April 1981)
INPUT/osjTptJy FUNCTIONS AND
PROCEDURES
Page 10—32
FUNCTION Fir,d(Name:
NameRecord): 800LEAN;
<Searches for specified record in EmpFl I.e
Returns
BEGIN
true If
found, leaving fiLe positioned at desired record.)
RecNum := ControlRecord.Fj
PrevlousRecN
0;
WHILE RecNum <> 0 DO rstDataRecord(wame.Lastcl)];
BEGIN
SEEK (EmpFl le,RecNum);
GET(EmpFite);
IF
THEN BEGIN Find:TRUE; EXIT(Fjnd)
Pre',iousRecNum
:
RecNum;
ReeNijo
:
EmpFlle.NextDataRecord;
END;
Find
: FALSE;
END (Find) ;
END;
FUNCTION Remove(Name: NameRecord):
BOOLEAN;
(Deletes specified record in EmpFlle.
Returns false if nt found.)
VAR NextRecNuqn: INTEGER;
BEGIN
Remove
:
TRUE;
IF Find(Name) THEN
BEGIN
NextRecNum
:
EmpFile.NextDataRecord;
Empri te.NextunusedRecord :
ControtRecord.Fi rstUnusedRecord:
ControtRecord.FjrstUnusedRecord := RecNum;
PUT(EmpF.i.Le);
IF PreviousRecNum = 0
THEN ControtRecord.Fjr*tDataRecor.d(Name.LastCl)]
NextRecNum
ELSE
BEGIN
SEEK(EmpFl le,PreviousRecNum);
GET(EmpFi te);
EmpFi 1e .NextDataRecord :
NextRecNuqn;
PUT(EmiFi Ic);
END;
SEEK(EmpFl le,O);
Empri te :=ControlRecord;
PUT(Empri Ic);
END
ELSE (Name not found) Remove
:
END (Remove) ;
False:
.
(Changed 30 April 1981)
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—33
FUNCTION NamePrecedesName(Namel,Name2: NameRecord>: BOOLEAN;
(Returns TRUE if Namel < Name2)
BEGIN
NamePrecedesName
IF Namel.Last <=
THEN TRUE
Name2.Last
ELSE IF Namel.Last =
Name2.Last
THEN IF Namel.First <
Name2.First
THEN TRUE
ELSE IF Namel.First =
NameZ.Ftrst
THEN Namel.Middle Ct Name2.MlddLe-
ELSE FALSE
ELSE FALSE;
END CNamePrecedesName) ;
FUNCTION Add(Emptoyee: EmpRecord): 800LEAN;
(Adds specified employee record to EmpFlte.
Returns false If no room remains to add record.)
VAR
BEGIN
InsertionPolntFound: BOOLEAN; NewRecNum: INTEGER;
Add TRUE;
RecNum := ControiRecord.FirstDataRecordCEmptoyee.Name.LastEl]];
PreviousRecNum :=
0;
InsertionPointEound
:
(RecNum =
0);
WHILE NOT InsertionPointFound DO
BEGIN SEEK (Empfi le,RecNum);
GET
(EmpFi te);
IF NameprecedesName(Emptoyee.4lame,EmpFi 1e .Name)
THEN InsertlonPointFound TRUE
ELSE BEGIN PreviousRecNum
:
ReeNum;
RecNum
: = EmpFi Le .NextDataRecord;
InsertlonPointFound :
(RecHum
0);
END;
END (Search for insertion point) ;
IF RecNum <> 0 THEN
IF SameNames(Emptoyee.Name,EmpFi 1e.Name) THEN
BEGIN Employee.NextDataRecord
:
EmpFi te.NextDataRecord;
EmpFi 1e
:
Employee;
PUT (EmpFi te);
EXIT(Add);
END;
IF
0 =
(NewRecNum
:
ControtRecord.FirstUnusedRecord) THEN
BEGIN Add
:
False 'CEmpFite is full);
EXIT(Add);
END;
SEEK (EmpFl le,NewRecNum);
GET (EmpFi te);
ControtRecord.Fj rstUnusedRecord :=EmpFi le'.NextUnusedRecord;
EmpFi 1e :EmployeeRecord;
EmpFjle.NextDataRecord
PUT(EmpFi Ic);
RecNum;
INPIJT/OuyptJT FUNCTIONS
AND PROCEDURES
Page 10—34
IF PrevlousRecNum
= 0 THEN
BEGIN
SEK(EmpFfle,o);
ControlRecord.Fj rstDataRecordrEmptoyee
: NewRecNum;
EmpFite
:
PUT (EmpFl te);
ControtRecord;
END
ELSE
BEGIN
SEEK(EmpFi te,Prev'iouiRecNum);
GETtEmpFI le);
EmpFi te.NextDataRecord
:2 NewRecNum;
PUT (EmpFi te);
END (Add)
END;
;
Name Last (1)]
PROCEDURE CreateEmptoyeej te(Size:
INTEGER);
(Create/Recreate Employee File with specified number of empLoyee records)
VAR
X,Slzelnetocks: INTEGER; CH: CHAR;
BEGIN
Sizelnstocks := 1
+ (Size+1) DIV (512 DIV SIZEOF(EmpRecord));
X := FSPEC(EmpFlte,'EPIPFIL','DAT');
CLOSE(Emprite); (Close fite If it is open)
ERASE(EmpFile); (Erase tHe if it already exists)
CREATE (EmpFi Le.SizelnBtocks);
OPENR(EmpFi Ic);
ControlRecord.F1 rstUnusedRecord
:
1;
FOR CH :2 'A' TO '1' DO ControLRecord.PlrstDatReCOr(Ij]
:
0;
EmpFl Le
:= Control.Record;
PUT(EmpFite);
FOR X
:
BEGIN
1 TO Size—i DO
EmpFlle.NextUnusedRecord :
X+1;
PUT (EmpFi Le);
END;
EmpFiLe.NextunusedRecord :
0;
PUT (EmpFi Le);
CLOSE (EmpFI Ic);
END 'CCreateEmptoyeeFji.e)
;
PROCEDURE OpenEmpFi le;
BEGIN OPEN(EmpFi Le,'EMPFIL',RANDOpfl;
ControtRecord
:
EmpFile;
END;
FUNCTION Yes(Message: STRING): BOOLEAN;
VAR
Answer: STRING;
BEGIN
WRITE(Message,' '); READLN(Answer); LCS(Answer);
IF Answer = 5" OR Answer = 'yes'
ELSE IF Answer =
THEN Yes
: TRUE
'ii' OR Answer = 'no' THEN Yes
: FALSE
ELSE Yes : Yes('?Please answer yes or no:');
END (Yes) ;
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
Page 10—35
PROCEDURE Introduction;
VAR
Quantity: INTEGER;
BEGIN
-
CRT(—1,.O);
WRITELN('
(Clear Screen)
AlphaPascal Random Pile Demonstration');
WRITELN;
WRITELN;
IF Yes('Do you wish to (re—)create empLoyee fiLe?') THEN
BEGIN
WRITE('How many records to yout wish to use?
);
READLN(Quantity);
WHILE Quantity < 1 OR Quantity > 100 DO
BEGIN
WRITE('?Ptease enter a number between 1 and 100: ');
READLN(Quantity);
END;
CreateEmpLoyeeFl le(Quantlty);
END;
OpenEmpFi Ic;
CRT(—1,0);
END (Introduction) ;
(CLear screen)
PROCEDURE GetName(VAR Name: NameRecord);
(Note: UCS onLy works on strings, and MiddLe is of type CHAR)
VAR
S;STRINGC1];
BEGIN
WITH
Name DO
BEGIN WRITE('Last
Name = '); READLN(Last); UCS(Last);
WRITE('First Name = '); READLN(First); UCS(Plrst);
WRITE('Middtetnitial = '); READLN(S); UCS(S);
Middle
:
IF S'' THEN '
'
ELSE Sri];
END;
END;
PROCEDURE GetEmployeeln-fo(VAR Employee: EmpRecord);
BEGIN
WITH EmpLoyee DO
BEGIN
WRITE('How old is ',Name.First,'? ');
READLN (Age);
WRITE('Is ',Name.First);
Sex :=
IF Ves(' male?')
THEN Male ELSE FemaLe;
END;
END (GetEmptoyeelnfo) ;
INPUT/outpuT FUNCTIONS
AND PROCEDURES
Page 10—36
PROCEDURE ShowEmPtoyeeInfo(Effiptoyee.
BEGIN
WITH EmpI.oyee,Nj
BEGIN
DO
EmpRecord);
END;
END;
WRITE(Last,', ',First,'
WRITE(Age,'
',Middle,': years old, 9;
WRITELN('sex: ',CASE
Sex OF
Male:
'mate;
Female: 'female';
ELSE '');
');
PROCEDURE ProcessRequests;
VAR
Option: CHAR;
PROCEDURE ListEmployees;
VAR
CH: CHAR; Count: INTEGER;
BEGIN
Count
:
WRITELN;
0;
FOR CH := 'A' TO 'V DO
BEGIN
RecNum
:
Control,Record.FjrstDataRecordccH];
WHILE RecNum <>
0
DO
BEGIN SEEK(EmpFi le,RecNum);
GET (EmpFi te);
ShowEmptoyeeIflfo(EmpFj 1e);
RecNum
:
Count +=
1;
EmpFi 1e.NextDataRecord;
END;
END;
WRITELN; WRITELN('Totat of ',Count,' employee(s)');
END CListEmployees}
;
PROCEDURE AddEmployee;
VAR
Employee: EmpRecord;
BEGIN
GetName(Employee.Name);
IF Flnd(Emptoyee.Name) THEN
BEGIN
WRITELN('?Emptoyee already on file');
EXIT(AddEmployee);
END;
GetEmployeelnfo(Emptoyee);
IF NOT Add(Emptoyee) THEN WRITELN('Thot enough room to add');
END {AddEmployee}
;
I
.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES Pege 10—37
PROCEDURE ChangeEmptoyee;
VAR
Name: NameRecord;
B EGI N
GetName(Name);
IF Find(Name) THEN
BEGIN
ShowEmptoyeelnfoCEmpFi te);
GetEmptoyeelnfo(EmpFi Led');
PUT(EmpFlte);
END
ELSE WRITELN('?Not fgund');
END <ChanqeEmployee> ;
PROCEDURE DeleteEmployee;
VAR
Name: NameRecord;
BEGIN
Get Name(Name);
IF NOT Remove(Name) THEN WRITELN('?Not found');
END {DeLeteEmptoyee> ;
PROCEDURE Inquire;
VAR
Name: NameRecord;
BEGIN
GetName(Name); tF Find(Name) THEN ShowEmptoyeelnfo(EmOFILC)
ELSE WRITELN('?Not found');
END (Inquire) ;
BEGIN CProcessRequests)
REPEAT
WRITE(
'Enter option CA)dd, C)hange, D)eIete, I)nquire, L)lst, Eult): ');
READLN (Option);
CASE Option OF
'a','A': AddEmptoyee;
'c','C': ChangeEmptoyee;
'i','I':
Inquire;
'L','L':
ListEmptoyees;
'q' /0': EXIT(ProcessRequests);
ELSE WRITEL.N('flnvalid option');
WRITELN;
UNTIL FALSE (I.e., until EXIT)
END (ProcessRequests) ;
(Changed 30 Aorll 1981)
INPUTFOUTPUT FUNCTIONS
AND PROCEDURES
PROCEDURE TerminationS
BEGiN
CRT(l,0);
Clear screen}
WRITELNYLe4v1ng ALphaPascal
END (Termination>
;
Random File Demonstration);
BEGIN (Program)
Introduction;
P ro C es $ Re ques t
Terminat ion;
END (Program)
5;
Page 10—33
10,3,3
Program Organization
We would just
like to point out that
broken up into modules been a good idea to do so,
43,2,2,
The
Include
Ootion the
($1),)
program above could have been and linked as separate files.
In fact, it would have consider taking the first include files (see below), if we were going to break it up, we might two global type declarations and putting them into
(For information on include files, see
Section
Then we might have made the FIND function a module, FIND,PAS,
10,3,3,1
The AMOS file NAMREC,INC
TYPE NameRecord
RECORD
First: STRINGEI1];
Middle: CHAR;
Last: STRtNGC1S];
END C NameRecord );
10,3,3,2
The AMOS file EMPREC,INC
TYPE
EmpRecType = (Control, Data, Unused);
EmpRecord
RECORD
CASE EmpRecType OF
Data:
Name; NameRecord;
Age: INTEGER;
Sex: (Male, Female);
NextDataRecord: INTEGER);
Control:
FirstDataRecord: ARRAY
FirstUnusedRecord: INTEGER);
Unused:
NextUnusedRecord: INTEGER);
END (EmpRecord)
;
EmpFi leType = FILE OF EmpRecord;
(Changed 30 April 1981)
OF INTEGER;
.
INPUT/OUTPUT FUNCTIONS AND PROCEDURES
10.3.3.3
Ttie AMOS fite
FIND.PAS
—
Page 10—39
MODULE FIND;
CS! NAMREC.INC)
'CS!
EMPREC.INC}
EXTERNAL FUNCTION SameNames
(Namel, Name2: NameRecord): BOOLEAN;
EXTERNAL VAR
EmpFite : EmpFiteType;
RecNum, PrevlousRecNum: INTEGER;
FUNCTION Find(Name: NameRecord): BOOLEAN;
(Searches for specified record in EmpFlle.
Returns
true if found, leaving file positioned at desired record.)
BEGIN
RecNum
:
ControlRecord.Fi rstDataRecord(Name.LastCl]];
PreviousRecNum :z 0;
WHILE
RecNum <> 0 DO
BEGIN SEEK(EmpFl le,RecNum);
GET(Empfi
Ic);
IF
SameNamesCName,EmpFiIe.Name)
THEN BEGIN Find:TRUE; EXIT(Find) END;
PreviousRecNum
RecNum
RecNum;
:= EmpFlte.NextDataRecord;
END;
Find
:
FALSE;
END (Find) ;
.
CHAPTER 11
MISCELLANEOUS FUNCTIONS AND PROCEDURES
The functions and procedures described in this chapter perform a variety of functions such as allowing your programs to position the cursor on the terminal screen and manipulating dynamic variables.
The functions and procedures discussed in this chapter are:
CHR
ORD
PRED
SUCC
KILCMD
NEW
MARK
RELEASE
CRT
CHARMODE
LINEMODE
INCHARMODE
Convert ASCII value to its character representation
Returns ordinal number of element in scalar type
Returns predecessor (i.e., previous item) of scatar type
Returns sucessor (i.e., next item) of scalar type
Abort command file execution
Creates new dynamic variable
Marks element en the heap
Releases element on the heap
Position screen cursor, and enable certain terminal display options
Sets terminal Into Charmode; suppresses echoing
Returns terminal from Charmode to line mode
Returns Boolean value telling you whether you are in Charmode or not
11.1
BASIC FUNCTIONS AND PROCEDURES
11.1.1
CHR
Alt characters displayed by the computer are members of the ASCII character set, and have a number (áalled the ASCII value) associated with them.
The
CHR function returns the ASCII character associated with a specified
ASCII value.
It accepts a positive, decimal INTEGER argument and returns a CHAR result.
The function invocation takes this form:
MISCELLANEOUS FUNCTIONS AND PROCEDURES
Page 11—2
CHR (number);
For example:
WRITELN(CHR(65)); prints the character A.
(65 character "A".) is the decimal
ASCII value of the
ASCII
11.1.2
KILCMD
It is often convenient to set up command files that automaticatly Invoke a series of system commands and file is a text file; each
Pascal. programs.
tine contains
(Remember data or specification.
To execute the entire set of thmmand and program invocations contained ,n the command file, supply just the name a that a command valid AMOS file of the command file at
AMOS command level.)
The
KILCMD procedure tells PRUN to abort any command file execution.
You probably will. use KILCMD if an error occurs that woutd make continuing the execution of the commmand file awkward.
The Invocation takes this form:
KILCMD;
As an example of the use of KILCMD, consider the command file PCL that accompanies this release of Alphapascal.
The PCL links a Pascal source file.
command file compiles and
Suppose you suppty to PCL the name of a source file that does not exist.
If the compiler can't compite your program, then
PLINK can't link it.
So, CMPILR itself contains a KILCMD procedure call that is executed if a compilation fails; the system stops any command file being executed and returns you to AMOS command leveL.
For
Information on error handling and writing your own errortrap routine, see Chapter 14, "Systems Functions and Procedures."
11.1.3
MARK
MARK is used in combination with RELEASE to store and release dynamic variables allocated via NEW (see below) in a stack—like structure called the
"heap."
The invocation of MARK takes this form:
MARK(vari able—identifier); where variable—identifier specifies a pointer variable that points to any type (typically, INTEGER).
MARK returns the current state of the heap.
That is, It returns the current address of the top of the heap.
MISCELLANEOUS FUNCTIONS AND
PROCEDURES
Page 11—3
A
"heap" or
"stack" can be considered as a sequential list in which items may only be inserted or deleted from one end oi the list.
In the reverse of the
Itens are deleted order in which they were entered on the stack.
•
The NEW procedure allocates you dynamic variables on the heap.
For exampLe, if use MARK, then perform a NEW, then use MARK again,
MARK will return two different values, since the top of the heap changes when you allocate the dynamic variable.
By doing a MARK followed by a NEW, you have a: value that tells you where on the heap the variable allocated by NEW is
Located.
The way to free up heap—space used by the dynamic variables allocated via NEW is to use RELEASE
(see Section 11.1.7, below).
NOTE:
Be very careful when using
MARK andRELEASE; unwise use of these procedures can Leave you pointing to areas of memory that are not oert of the heap, thus causing unpleasant and unpredictable results.
11.1.4
NEW
The
NEW procedure form: allocates a dynamic variable.
The invocation takes the
NEW(vari able—identifier); where variable—identifier is the pointer to the variable allocated by NEW.
To access the variable allocated via
NEW, use the pointer variable variable—ider,tifier.
(For more information on NEW and dynamic variables, see Section 7.2.8, "Pointer Type.") The sections on MARK and RELEASE In this chapter give information on using MARK, NEW, and. RELEASE to allocate and dc—allocate dynamic variables on the "heap."
11.1.5
ORD
The ORD(X) function returns the ordinal nisnber of the argument in the scalar data type of which X is a member.
user—defined scalar types.
Accepts arguments of type
CHAR or
Returns an
INTEGER result.
The function invocation takes this form:
ORD(variable—identifjer or constants);
For example, each character displayed by the computer has a numeric value associated with it (called the ASCII value), which specifies its position in the set of
ASCII characters.
If you use the ORD function on an ASCII character, ORD will return to you the ASCII value of that character
(that is, its ordinal number in the ASCII character set).
For example:
WRITELN(ORD('A'));
(Changed 30 April 1981)
MISCELLANEOUS FUNCTIONS AND PROCEDURES Page 114 returns the decimal number 65, the ASCII value of the character
You may also include an identifier for a user"defined scalar type,
For example:
PROGRAM TestOrd;
TYPE DAYSOFTHEWEEK = (MON,TUE,WED,THUR,FRI);
BEGIN { Testord }
WRITELN(Ordinal number of THUR is: ,ORD(THURfl;
WRITELNYOrdinaI number of
D
END { TestOrd },
is: ,ORDVDfl)
The
ASCII program above prints the ordinal number of the character
"D" in the character set, and the ordinal number of "THUR" in the userdefined scalar type DAYSOFTHEWEEK,
(NOTE: The ordinal numbers for the elements of
DAYSOFTHEWEEK are: MON = 0,
TUE =
1, WED = 2, THUR = 3, FRI = 4,)
11,16
PRED
The
PRED function returns the predecessor of the specified scalar argument,
The invocation of the PRED function takes this form:
For example, let°s say that we defined the scalar type Cardinal to contain the elements: First, Second, and Third:
TYPE
Cardinal = (First, Second, Third);
Since the elements of a scalar data type are ordered, we can find out what element is previous to the specified item by using the PRED function,
For cx amp l e:
IF PRED(Second) First THEN WRITELNCC0rrect! ');
The value returned by PRED is not a variable or an expression; therefore, trying to use WRITE or WRITELN to display that value causes an error,
(That is, you may not say: WRITELN(PRED(Second)),)
PROGRAM TestPred;
TYPE
VAR
Daysoftheweek = (Mon,Tue,Wed,Thu9Fri);
Day
:
Daysoftheweek;
BEGIN { TestPred }
:
Tue;
IF PRED(Day) = Mon THEN WRITELN('Today is Tuesday');
Day
:
PRED(Day);
IF Day = Mon THEN WRITELN('It''s Blue Mondayl')
END C TestPred },
(Changed 30 4pril 1981)
.
MISCELLANEOUS FUNCTIONS AND PROCEDURES
When you run the program above, it prints:
Today is Tuesday
It's Blue Monday!
Page 11—5
11.1.7
RELEASE
The RELEASE procedure is used with MARK and NEW to use dynamic variables with a stack—Like structure catted the "heap."
(See Section 11.1.3, "MARK," for information on the heap.) It deallocates the dynamic variabte at the specified heap location.
The RELEASE invocation takes the form:
RELEASE (variable—identifier); where variable—identifier is the same argument as that supptied to MARK.
For example,
If you use MARK to get the current state of the heap, use NEW to attocate a dynamic variable (which advances the top of the heap past the value returned by the previous MARK), and then use RELEASE with the value returned by the previous MARK, RELEASE de—attocates the dynamic varlabte from the heap.
A picture might hetp to clarify:
Procedure
The Heap
NEW(VO)
MARK(LocationVl)
NEW(V1)
MARK(Locat ionV2)
NEW(V2)
VO
Vi
V2
Then:
Use RELEA5E(Locationv2)
Use RELEA$E(LocationVl)
RELEA$E(Locatjonv2) de—attocates v2; RELEASE(Locatlonvl) dc—allocates VI.
Va is left on the stack in the example above.
You cannot RELEASE a dynamic variable in the middle of the heap; you may only release variables from the bottom of the list.
NOTE: Be very careful when using MARK and
RELEASE; unwise use of these procedures can leave you pointing to areas of memory that are not part of the heap, which can cause severe problems.
11.1.8
SUCC
The SUCC procedure allows you to determine the successor element tQ the sepcifjed scalar constant.
The invocation takes the form:
SUCC(element);
MISCELLANEOUS FUNCTIONS AND PROCEDURES
Page 11"ó where example: element is
a variable"identifier or constant of a scalar type,
For
PROGRAM;
VAR mt
:
INTEGER; bat
:
(YES, NO, Y, N);
BEGIN
WRITEYEnter integer: ); READLN(Int);
WRITELN(SUCC (Intfl; bat
:
YES;
END,
IF SUCC(Dat) = NO THEN WRITELNYYES)
If you enter the number 11 to the program above, it prints:
12
YES
(See also Section 11,6, "PRED," for more information on manipulating scalar types,)
11,2
SPECIAL TERMINAL DISPLAY PROCEDURES
.
11,2,1
CHARMODE
The
CHARMODE procedure allows you to set the terminal of the user of your program into character mode,
When a terminal is in character mode, your program is able to read keyboard input a character at a time, even before a terminating carriage return is typed,
(Assembly language programmers on the
AMOS system may recognize this input mode as "image mode,")
The invocation of this procedure takes this form:
CHARMODE; a
Character mode is useful for checking special input such as passwords, since the characters are not echoed at the time they are input, but when read (via
GET or
READ).
To inhibit echoing, use the predeclared KEYBOARD file
identifier,
NOTE: Character editing terminal is in character the
LINEMODE procedure program exits to monitor into LINEMODE,
(such as RUBs or Controi"Us) doesn't work when mode,
To return a terminal to the normal mode,
(discussed in
Section 11,2,3, below).
When level, AMOS automatically puts the terminal the use your back
MISCELLANEOUS FUNCTIONS AND PROCEDURES
Page 117
11,22
C.RT
The
CR1
In addition, you can aLso select certain terminaHhandLing options (such clear screen, delete character, etcj,
The function invocation takes this form:
C PT (A rgl
, A rg2) ; as where Argi assumes that negative, screenhandl and Arg2 are integers, you want to position the
CR1 assumes ing options, that you
If Arg1 want to is positive, the CR1 cursor on the screen; use one of
if
the function
Arg2 is ext ended
11 22,1 positive, coordinates positioned, coordinates
Cursor Positioning " If the first argument you supply to then the CR1 function reads both arguments as the X,Y row specifying the screen
(The top position where you want the lefthand corner of the screen is specified
1,1,)
For example, the function:
CR1 is
/ column cursor by the
CR1 (12, 35) positions the cursor at the 12th row and 35th column of the screen,
NOTE:
If you supply row and column coordinates that are out of range for your terminal, unpredictable results éould occur,
11,2,2,2
Extended Screen to CR1 is negative, the CR1 extended terminaHhandling example, the function:
Display Options " If the first argument supplied function assumes that you want to use the options specified by the second argument,
For
CRT L"l ,O); tells CRT to select option #0, the clear"screen option.
MtSCELLANEOUS FUNCTIONS AND PROCEDURES
Page 11—3 o
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
The screen—handling-options provided are:
Code
24
25
26
27
Function
Clear screen
Cursor home (upper left corner)
Cursor return (coLumn 0 wIthout line—feed)
Cursor up one row
Cursor down one row
Cursor left one column
Cursor right one column
Lock keyboard
Unlock keyboard
Erase to end of line
Erase to end of screen
Protect field (reduced intensity)
Unprotect field (normal intensity)
Enable protected fields
Disable protected fields
Delete line
Insert line
Delete character
Insert character
Read cursor address
Read character at current cursor address
Start blinking field
End blinking field
Start line drawing mode (enable alternate character Set)
End line drawing mode (disable alternate character set)
Set horizontal position
Set vertical position
Set terminal attributes
NOTE: You should be aware that these options can be selected only if your particular terminal and terminal driver program are capable of carryinq them out.
(For example, not all terminals can perform an erase—to—end—of—screen function.) Note that most terminals do not support all of the options listed above; unsupported options wilt be ignored by your terminal driver.
11.2.3
INCHARMODE
The INCHARMODE function returns a Boolean result.
If it returns a
TRUE, then you are in charmode; a FALSE indicates that you are in linemode.
(See the paragraph below.)
.
MISCELtANEOUS FUNCTIONS AND
PROCEDURES
Page 11—9
1L24 LINEMODE
The LINEMODE procedure has returns a terminal to the normal input mode after it been set into character mode via the CHARMODE
Section 1h21, above),
The invocation procedure takes this form;
(discussed in
LINEMODE;
While in line mode, all input is editing is ended by a enabled,
Character echoing carriage occurs return, and character as you type the characters, not when they are read,
CHAPTER 12
MATHEMATICAt FUNCTIONS following functions accept one or more numeric arguments.
information on invoking functions and on writing your own
For functions, see
12.1
TRIGONOMETRIC FUNCTIONS
12.1.1
COS(X)
Cosine trigonometric function.
Accepts a
REAL or INTEGER argument and returns a
REAL result.
Argument must be in radians.
12.1.2
SIN(X)
Sine trigonometric function.
Accepts a REAL or INTEGER argument and returns a REAL result.
12.1.3
TAN(X)
Tangent trigonometric function.
Accepts a
REAL or
INTEGER argument and returns a REAL result.
(Changed 30 April 1981)
MATHEMATICAL FUNCTIONS
Page 12—2
12.1.4
ARCCOS(X)
Arc cosine trigonometric function.
Computes the inverse cosine function.
(See COS above,) Accepts a REAL or
INTEGER argument and returns a
REAL result. X mUst be greater than or equal to —1, and tess than br equat to 1.
12.1.5
ARCSIN(X)
Arc sine function.
Computes the inverse sine function.
(See SIN above.)
Accepts a REAL or INTEGER argument and returns a
REAL result.
X must be greater than or equal to —1, and less than or equal to 1.
12.1.6
ARCTAN(X)
Arc tangent trigonometric function. Computes the inverse tangent function.
(See TAN above.) Accepts a REAL or INTEGER argument and returns a
REAL result.
12.2
HYPERBOLIC TRIGONOMETRIC FUNCTIONS
12.2.1
COSH(X)
Hyperbolic cosine trigonometric function.
Accepts a
REAL argument and returns a REAL result.
Argument must be in radians.
or INTEGER
12.2.2
SINH(X)
Hyperbolic sine trigonometric function.
Accepts a REAL or INTEGER argument and returns a REAL result.
12.2.3
TANH(X)
Hyperbolic tangent trigonometric function.
argument and returns a REAL result.
Accepts a
REAL or INTEGER
(Changed
30 April 1981)
.
MATHEMATICAL FUNCTIONS
Page 12—3
12.2.4
ARCCOSH(X)
Hyperbolic arc cosine trigonometrjc function.
argument and returns a REAL result.
than or equal to 1.
Accepts a REAL or
INTEGER
(See ARCCOS above.) X must be greater
12.2.5
ARCSINH(x.)
Hyperbolic arc sine ,trigonometric function.
Accepts a
REAL argument and returns a REAL result.
(See ARCSIN above.) or
INTEGER
12.2.6
ARCTANH(X)
Hyperbolic arc tangent trigonometric function. Accepts a REAL or INTEGER argument and returns a REAL result.
(See ARCTAN above.) The absolute vatue of X must be less than 1.
12.3
MISCELLANEOUS MATHEMATICAL FUNCTIONS
12.3.1
ABS(X)
Computes the absolute value of tte argument.
Accepts one INTEGER or REAL argument, and returns an
INTEGER or REAL result.
For example: displays the answer:
32.123
12.3.2
EXP(X)
Exponential function.
Computes e to the X power, where e is the base of natural logarithms.
Accepts a
REAL or
INTEGER argument; returns REAL
result.
(Changed 30 April 1981)
MATHEMATICAL FUNCTIONS
Page 12—4
12.3,3
EXPONENT(X)
Computes K such that X and less than 1.
=
.1
*
2K,
where J is greater than or
Accepts a REAL argument.
equaL to
.5,
12.3.4
FACTORIAL(x)
Computes the factoriaL of result.
For exampLe:
X.
FACTORIAL(6.O) returns 720. (720 =
6*5*4*3*2*1.')
Accepts a REAL argument; returns a REAL
12.3.5
LN(X)
Computes the natural (Naplerian) argument; returns a
REAL result.
2.71828....) logarithm.
Accepts a
REAL or iNTEGER
Computes logarithm to the base e.
(e s
12.3.6
LOG(X)
Computes the log base ten of the argument.
argument; returns a REAL result.
Accepts a
REAL or INTEGER
12.3.7
ODD(X)
Tests for odd value.
Accepts INTEGER argument; returns a BOOLEAN resuLt.
If X is odd, ODD returns TRUE; if X Is even, ODD returns FALSE.
12.3.8
POWER(X,Y)
Computes X to the V power.
Accepts two REAL numbers; returns a REAL result.
For example:
POWER(2.0,3.O) returns 8. You can also use POWER to compute the
Pith root of a number——
POWER(X,1.0/N).
For example, to find the ctte root (third root) of 256.12:
POWER(256.12,1.O/3.O)
(Changed 30 ApriL 1981)
MATHEMATICAL FUNCTIONS
Q• 12—5
12,3,9
PWROFTEN(x)
Returns the
REAL value; returns a REAL value,
For example: value of ten raised to the power of X,
Accepts an INTEGER or
Accepts fractions and negative numbers.
PWROFTEN (3)
returns 10 to the third,
or 1000.
12,3,10
PWROFTWO(x)
Returns the value of two raised to the and returns a REAL value. Number power of X,
Accepts an INTEGER value must be greater than zero,
For example:
PWROFTWO(3) returns 2 to the third power, or 8,
12,3,11
RANDOMIZE
Randomizes the starting seed of the RND function (see below), arguments,
For example:
RANDOMIZE;
It takes no
12,3,12
RND
Returns a random REAL number between 0 and 1, cx amp Ic:
It takes no
PROGRAM TestRND;
C Generate 20 random integers between 1 and 10
1'
VAR
I
:
INTEGER;
BEGIN
RANDOMIZE;
WRITELN7Random numbers between 1
FOR
I
1
TO 20 DO
BEGIN
WRITELN(TRUNC( (RND*IO)+1 ))
END and 1O:fl;
END, arguments,
For
(Changed 30 April 1981)
MATHEMATICAL FUNCTIONS
Page
12—6
12.3.13
ROUND(X)
Rounds—off
X.
Accepts a
REAL argument; returns an INTEGER result.
For example, ROUND(2378) returns 24; ROUND(23.45) returns 23.
12.3.14
SHIFT(X,Y)
Performs binary multiplication by shifting Left the binary representation of the number specified by the first argument the number of places specified by the second argument.
For example:
SHIFT(7,2); returns the answer 28.
places is the
(The binary number 111 (7 deâimal) shifted Left two, binary number 11100 (28 decimal).) X and V must be of type
INTEGER.
12.3.15
SQR(X)
Computes the square of X.
For example, SQR(8) returns 64.
Accepts REAL or
INTEGER argument and returns an INTEGER or REAL result.
12.3.16
SQRT(X)
Computes non—negative square root of argument.
Argument may be INTEGER or
REAL; result is REAL.
X must be greater than or equal to zero.
Accepts a
REAL or INTEGER argument; returns a REAL result.
12.3.17
STR(X) and STR(X,a,b)
Converts numeric values to STRING.
returns a STRING.
Accepts a REAL or INTEGER number, and
You may optionally supply SIR with two INTEGER arguments that tell
STR how to format a converted number: or:
STR(Number,X,Y);
SIR (Number,X); where X specifies a minimum field width and V specifies the number of digits to write after the decimal point.
If the number is larger than the fieLd specified by X, PASCAL does not truncate the number, but prints the number using the necessary number of digit positions.
(Changed
30 April 1981)
.
MATHEMATICAL FUNCTIONS
I
Paqe 12—7
(If
Number" is
INTEGER, you may not specify Y,)
STR perform formatting in exactly that they do not generate a leading example? given the SEAL data 123,44: space
These two variations of the same way as WRITE and WRITELN, except for positive numbers,
For
WRITELN(5TR(123,44,1O,4fl; returns the string:
123,4400 where the number is rightjustified in a fieLd of ten blanks, and four
digits are written to the right of the decimal point,
12,3,18
TRUNC(X)
Truncates
X, ccepts REAL argument; returns INTEGER result,
(For example,
TRUNC(24,3) returns the integer 24,)
12,4
SAMPLE PROGRAM TO PAD A NUMBER WITH LEADING ZEROS
Below is a useful procedure to pad a number with leading zeros along with sample program that makes use of it: a
PROGRAM Format;
\/AR
STRING;
{ The procedure call Format(String,Left,Right,Number) formats the number with Left zero"filled digits before the decimal
point and Right zero"filled digits after the decimal point,
A trailing space Or minus sign is added to indicate the sign of the number,
Illegal arguments generate an error to
ERRORTRAP, )
PROCEDURE Format(VAR X
:
STRING; Left,Right
INTEGER; Num
:
REAL);
VAR Pow
:
Pow
:
REAL;
BEGIN { Procedure Format )
IF Left > 11 OR Left <
0 THEN ERROR(i);
PWROFTEN(Left);
IF ABS(Num) > Pow THEN ERROR(1) { Value range error
X:
STR(Pow + ABS(NumT,O,Right);
C Force leading zeros by adding power of ten and converting to STRING, }
DELETE(X,1,1); C Remove leading
1
)
X : IF Num C 0 THEN CONCAT(X,) ELSE CONCAT(X/ fl
END C Format };
BEGIN C Main program }
Format(S,S,2,—12,7); C Return answer in S )
WRITELN(° Format 5,2r127 =
,S)
WRITELN(Result should be OOO12,7O")
END C Main program ),
(Changed 30 April 1981)
.
CHAPTER 13
STRING AND CHARACTER ARRAY FUNCTIONS
AND PROCEDURES
This chapter contains descriptions of the standard functions and procedures you can use on data that have been declared as type STRING or packed arrays of type CHAR.
These functions and procedures have been pre—dectared for you by
AlphaPascat.
For a full tist of alt functions and procedures, refer to
Appendix A, "Quick Reference to AtphaPascat."
These are the functions and procedures described in this chapter:
For data of type STRING:
CONCAT
COPY
DELETE
INSERT
LENGTH
LCS
P05
STRIP
UCS
VAL
Concatenates specified strings
Copies specified string (or parttal string) Into another string
DeLetes specified nunber of characters from string
Inserts specified string (or partial string) Into another string
Returns ninber of characters In string
Converts upper case string to lower case
Returns position of specified character in string
Removes trailing spaces from string
Converts tower case string to upper case
Converts a string to a REAL nunber.
For data of type PACKED ARRAY OF CHAR:
FILLCHAR
MOVELEFT
NOVERIGHT
SCAN
Fills specified string with specified character
Copies specified nunber of characters beginning with
Left of array over to specified array
Copies specified nunber of characters beginning
with right of array over to specified array
Returns position of specified character in array
(Changed 30 April 1981)
STRING AND CHARACTER ARRAY
FUNCTIONS AND PROCEDURES
Psqs 13—P
13,1
STRING INTRINSICS
Below are the functions and procedures that you
STRING.
can use on data of type
131,i
CONCAT
The
CONCAT function returns a string
the specified string(s),
that contains the contents of aLl of
The function invocation takes this form:
CONCAT(Stringl ,String2,,
,
,St ringN); where you may specify one or more strings to be concatenated,
For example:
PROGRAM Testconcat;
VAR
Destination, Sourcel, Source2, Source3
:
STRING;
BEGIN { TestConcat
3' "urce1 :
"Nevermorefl";
Source2 := the Raven,
Source3
:
Quoth ';
Destination
:
CONCAT(Source3,Source2,Sourcel);
END
WRITELN(Dest mat ion)
'C TestConcat 3',
The orogram above prints:
Quoth the Raven, "Nevermore!
13, 12
COPY
The COPY function creates a new string of the specified number of characters whose contents are taken from the specified source string, starting at the specified index,
The function invocation takes this form:
COPY (Source"string,Index,si ze"of"returnedstring);
For example:
(Changed 30 April 1981)
STRING AND CHARACTER ARRAY
FUNCTIONS, AND PROCEDUR€s
Page 13—3
PROGRAM TestCopy;
VAR
Source, Target
: STRING;
Position :
INTEGER.;
BEGIN 'CTestCopy}
'urce :'Jonathan R.
Smith';
Position :=
POS('S',Source)
Target
:
COPY
'C Find position of Last name );
(Source,Position,5);
WRITELN('The customer last name is: ',Target);
WRITELN('Last—name position in
END (End TestCopy}.
source string ts: ',Position);
The program above prints:
The customer last name is: Smith and:
Last—name position in source string is: 13
(Notice that we used the POS function, discussed below in Section 13.1.7, to determine the position in the source string of the character 'S'.)
13.1.3
DELETE
The
DELETE procedure removes the specified number of characters from the
source string, starting at the specified position.
The procedure invocation takes this form:
DELETE (Source—string, Index, Number—of—characters); where Source—string must be a string variable.
For example:
PROGRAM TestDelete;
VAR Source
:
STRING;
Position, Size
:
INTEGER;
BEGIN 'C TestDelete )
Source :
'Now
Position
: is the time for all good men!';
POS('atl',Source);
DELETE (Source, Position + 3, 9);
WRITELN (Source)
END C TestDelete ).
The program above prints the string:
Now is the time for all!
STRING AND CHARACTER ARRAY FUNCTIONS
AND PROCEDURES Page 13"4
131,4
INSERT
The
INSERT destination procedure
string.
inserts the specified string into a specified
It begins the insertion at the specified position in
the destination string,
The invocation of this procedure takes the form:
INSERT(Insert'string,Destinationstring,Inde); where Destination'string must be a string variable,
For example:
PROGRAM Testlnsert;
VAR
Insertion,Destination
:
STRING;
BEGIN C Testlnsert )
Destination
:
Customer name is: ,;
Insertion : Robert Allen;
INSERT(Insertion,Destination,19);
WRITELN (Destination)
END C Testlnsert },
The program above prints:
Customer name is: Robert Allen,
13,1,5
LCS
The LCS procedure converts upper case characters to lower case.
The procedure invocation takes this form:
LCS (SourceString); where SourceString is the string to be converted,
For example:
PROGRAM TestLCS;
VAR
CustomerlD
:
STRING[221;
BEGIN C TestLCS }
CustomerlD := °Alfred J, Prufrock Jr,;
LCS (CustomerlD);
WRITELN(Converted name is: 5CustomerlD)
END C Te5tLCS ),
The program above prints:
Converted name is: alfred j, prufrock jr,
STRING AND CHARACTER ARRAY FUNCTIQNS,AND PROCEDURES
Page 13—5
13.1.6
LENGTH
The
LENGTH
function'
returns the
string.
The function invocation
number f characters. in the specified
takes this torn
LENGTH (Source—string);
For example:
PROGRAM Teskength;
VAR
State
: STRING;
BEGIN
C
TestLength }
State := 'California';
WRITELN('Number of characters in
END 'C TestLength ).
state: ',LENGTH(State));
WRITELN('Number of characters in zlpcode: ',LENGTH('90247'));
The program above prints:
Number of dharacters in state: 10 and:
Number of characters in zipcode: S
13.1.7
P05
The P05 function returns the pos4tion specified characters in the specified specified characters, it returns takes the form: a zero.
of
the
first.
source string.
The invocation occurrence of the
If POS can't find the of this function
POS (Pattern,Source—st ring);
For example:
PROGRAM TestPos;
VAR
Source :
STRING;
BEGIN C Testpos 3
Source := 'The requested account number is #AA234—567—23228';
WRITELN('The account number begins at character
POS( '#AA' ,Source))
position # ',
END C TestPos 3.
The program above prints the message:
The account number begins at character position # 33
STRING AND
CHARACTER
ARRAY FUNCTIONS AND PROCEDURES
Page 13—6
13.1.8
STRIP
The STRIP-procedure strips trailing blanks from the specified string.
-is,
STRIP removes any blanks that are at
(That the end of the string.) The invocation takes the form:
STRIP (Source5t ring); where SourceString must be a string variable.
For example:
PROGRAM TestStrip;
VAR
Source
:
STRING;
BEGIN -C TestStrip )
Source :=
25 characters
WRITELN('Before strlpping:(',Source,']');
STRIP (Source);
WRITEL.NC'After stripping:C',Source,']')
END -C TestStrip )-.
The program above prints:
Before stripping:C25 characters
After stripping:C25 characters]
]
13.1.9
UCS
The UCS procedure converts lower case characters in a specified string to upper case.
The procedure invocation takes the form:
UCS (Sourcest ring); where SourceString must be a string variable.
For example:
PROGRAM TestUCS;
VAR
Title
:
STRINGC3O];
BEGIN -C TestUCS )-
Title
:= 'fAmous comPUters i HAve known.';
UCS(Titte);
WRITELN('CQnverted title is: ',Title)
END -C TestUC5 ).
The program above prints:
Converted title Is: FAMOUS COMPUTERS I HAVE KNOWN.
STRING AND CHARACTER ARRAY
FUNCTIONS AND PROCEDURES
Page 13—6a
13.1.10
VAL
The VAL procedure converts the form: a string to a REAL nunber.
The invocation takes
VAL(SourceStrinq); where Sourcestrinq Is nunber.
For example: a string variable that you want to convert to a
PROGRAM TeStVAL;
VAR
Price :
STRING;
Total
:
REAL;
8EGIN C Test VAL )
WMTE('Enter price of object: ');
READLN(Price);
IF POS('.',Price) = 0 THEN WRITELNVThe price is in
Total
:
VAL(Prlce); whoLe dollars.');
WRITELN('Wlth 6% tax, the price is:',Total * 1.06:8:2)
END C Te5tVAL 3.
The program above uses a string function, P05, on the string Price; it then converts Price to a REAL nunber (Total) so that it can
Derform operation on the value.
In the Last WRITELN invocation to format the nireric nuneric
(Notice the use of the optional parameters (":8:2") answer in a field eight characters wide with two digits to the right of the decimal point.) a
A sample run of the program looks like this:
Enter price of object: 560
The price is in whole dollars.
With 6% tax, the price Is:
593.60
(Changed 30 ApriL 1981)
STRING AND CHARACTER ARRAY
FUNCTIONS 'AND PROCEDURES
Page 13—7
13.2
CHARACTER ARRAY INSTRINSICS
The procedures and strings
CHAR.
the listed below are for use on packed arrays of type
You must make sure that to an array of 24 eLements wilt
any string literat you asstgn to the
correct number of characters.
For exampi.e, nssigning cause an error if that less than or more than 24 characters.
a string literal,
string array is
Literal
has
13.2.1
FILL.CHAR
The
FILLCHAR procedure modifies
a character arçay by filLing it with the
specified character.
The invocation for the procedure takes this form:
FILLCHAR (Destination,Length,Fj llrcharacter); where Destination must be a variable.
For example:
PROGRAM TestFi ItChar;
VAR
Destination
: PE%ED ARRAY C1...1Q] OF CHAR;
Length
:
INTEGER;
Character :
CHAR;
I
INTEGER;
BEGIN 'C TestFillChar I
Length
:
10;
Character
:
'A';
FILLCHAR (Dest I nati on,Length,Character);
FOR I
:
I TO 10 DO
WRITE (Des'ffnatl'EtI3)
END 'C TestFllLChar I.
The program above fills the character array Destination with ten A's.
13.2.2
MOVELEFT and MOVERIGHT
The MOVELEFT and MOVERIGHT procedures can be dangerous if not used correctly. (For exampte, if you teLl these procedures that you want to only contains
10 memory?) bytes, where do move blocks of bytes in memory.
They one of move 20 byt,, but the the extra, destination array
10 bytes go? Somewhere in within a single array.
array of type CHAR to another.
characters
You can also use them to move characters from one
MOVELEFT starts at the left of the specified source array, and to the
left).
specified position in the destination array (also beginning at the
MOVERIGHT moves bytes beginning with the right moves bytes of the source array,
STRING AND CHARACTER ARRAY FUNCTIONS
AND. PROCEDURES
Page 13—8 and beginning with the right of the specified locations in the destination array.
of
Yop specify the source array, the destination array, and the number bytes to move.
(In the case of an &rray of type CHAR, one byte is one character.) By including subscripts, you may spcify the locations in the source and destination arrays at which to start..
Of course,
MOVELEFT and MOVERIGHT do not physically "move" the bytes; instead, they make a copy of the specified bytes from the source array
Into the specified locations of the destination array.
The invocations of
MOVELEFT and MOVERIGHT take this form:
MOVELEFT(Source—array,Destination—array,Number—of—bytes); and:
MOVERIGHT (Source—array,Destination—array,Number—of—bytes); where Destination must be a variable.
Given the same arrays and same subscripts, the results of
MOVERIGHT and
MOVELEFT will look exactly the same.
For example, if Source is the packed array of CHAR "1234567890", and Destinati9n is the packed array of CHAR
MOVELEFT (Source(6]
,
Desti nat iont6],5);
MOVERIGHT (Sourcetó],DestlnationC6],5) ;
will
produce the same packed array: *****67890.
The MOVELEFT procedure above moves the characters in this order: 6, 7, 8, 9, and 0.
The
MOVERIGHT procedure above moves the characters in this order: 0, 9, 8, 7, and 6.
The only time this will become Important is when you are moving characters within the same array.
For example:
PROGRAM TestMove;
VAR
Source
:
PACKED ARRAY C1.23] OF CHAR;
BEGIN
C
TestMove >
Source :=
'Days are never too long';
MOVELEFT (SourceC63,SourceCl ],IO);
WRITELN (Source);
Source
'Days are never too long';
MOVERIGHT($ourcet6],SourceCl ),10);
WRITELN (Source)
END C TestMove ).
The program above prints: are never ever too long
STRING AND CHARACTER ARRAY
FUNCTIONS. AND PROCEDURES
Page 13—9 and: ever ever ever too long
MOVERIGHT and MOVELEFT can produce radically different results, depending the data you give them.
on
You must be careful to choose the correct MOVE
function for yourparticutar
application.
13.2.3
SCAN
The SCAN function returns the number of characters In the array beginning of the array until the specified character.
characters are not found, SCAN returns the number of characters entire array.)
The function invocation takes this form: from the
(If the specified
in the
SCAN (Length,Partial—expression,Source—array); where Length gives the length of the array, Source—array specified the packed array of type CHAR that is to be searched, and
Partial—expression takes the form:
<> character—expression or:
= character—expression
For example:
PROGRAM Test5can;
VAR
Source
:
PACKED ARRAY C1..25] OF CHAR;
BEGIN C TestScan )
Source := 'Error:30240 type RETURN
END C TestScan 3.
';
WRITELN('Error code starts after char #: ',SCAN(25,=':',Source))
If the searched for character—expression array, SCAN returns a zero.
Is
the first character of the
By specifying a negative length, you can backward, from array, SCAN then right
left.
tell
SCAN to scan the array
If the specified character appears in the returns a negative number characters scanned from the character was reached.
to specify the position in
For example: specifying the number of right of the array before the specified
If you supply a negative length, be sure to also the array at which you wish the search to start.
WRITELN('zt starts after character #',SCAN(—25,=':',Source(25]));
.
PART III
ADVANCEDPROGRAMMING ON THE ALPHA PASCAL SYSTEM
S
S
CHAPTER 14
SYSTEMS FUNCTIONS AND PROCEDURES
The following functions and procedures will be of special use to the experienced AtphaPascal programmer.
They allow you to determine the
Location and size of data objects in memory, to determine the amount of free memory Left, and to handle system and fileerrors.
Other functions and procedures alLow you to access system functions such as accessing the Line printer spooler, mounting disks, reading the system clock, and reading, setting, and releasing multi—user file locks.
14.1
LOCATION
The LOCATION function returns an integer that corresponds to the absolute memory address of the specified variable.
The invocation takes the form:
LOCATION(variabl.e—identlfier); where variable—identifier specifies the variable whose memory address you wish to know.
LOCATION accepts a variabLe af any type as an argument.
LOCATION may not be used on packed fields.
14.2
SIZEOF
The SIZEOF function returns the size (in decimal bytes) of the specified item.
The invocation takes this form:
SIZEOF(variable—or—type—identl fier);
For example:
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14—2
PROGRAM TestSizeOf;
TYI!E
-
SampleRecord = RECORD character: CHAR; next: $ampleRec.ord;
END;
BEGIN ( Test5izeOf )
VRITELN('$ize of SampleRecord (in bytes) is:',SIZEOF(SampleRecord))
END 'C TestSizeOf }.
The program above prints:
Size of SampleRecord (in bytes) is: 4
14.3
MEMAVAIL
MEMAVAIL returns an integer corresponding to 3/4 the number of unused words remaining in the user partition.
This number can be used to estimate how many items can be aLlocated by NEW before memory capacity is exceeded.
You can use SIZEOF to determine how many bytes any require.
particular object
wilt
.
14.4
MAINPROG
MAINPROG is a boolean function that returns no arguments.
It returns TRUE if the .PCF file is being used as a program, or FALSE if it is being used as a Library.
MAINPROG can be used for debugging purposes.
It can be used to write a program which can also be used as the library of a checkout program that makes sure that the functions and procedures defined in the original program
(now a Library to the checkout program) are impt!mented
correctly.
this, the program would have the form:
To do
PROGRAM;
.dectarations.,.
BEGIN
...initialization...
IF MAINPROG THEN
BEGIN
<statements)
END;
.
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14—3
The statements are only executed if the program is being used as a program and not asa library.
The checkout program testing the functions and procedures in the above program would then declare them as EXTERNAL functions and procedures in order to call them with test arguments.
14.5
SPOOL
SPOOL is an assembly language routine that you can call from Pascal to spool a disk file to the tine printer(s).
(To "spool" a tile is to insert it frito the printer queue, after which you can continue to do other things while your file waits in the queue for its turn to be printed.) SPOOL allows you to specify on which printer the file Is to be printed, the number of copies to be printed, the form on which it is to be printed, whether the file is to be deleted after it is printed, etc.
The current version of SPOOL (AMOS version 4.4/AtphaPascal version 2.0, and later) is fully compatible with the current BASIC SPOOL subroutine.
In other words, the only information you must suppty to
SPOOL is the specification of the file you want to print; all other parameters are optional.
However, any unspecified arguments must be replaced by a null value (STRING null or INTEGER 0, based on the typ of the argument).
This is because Pascal functions and arguments.
procéduteé
,equlre a fixed number of
The following definitions of switches and error codes are provided
In the include file
SPOOL.INC.
place in your program.
To use, insert (SI SPOOL}lnto the appropriate
14.5.1
Switches
To make life easier, switch values are available as constants.
description of SWITCHES, see betola.
The constants wouLd be:
BANNER =
NOBANNER =
DELETE =
NODELETE =
HEADER =
NOHEADER =
=
NOFF =
WAIT =
1;
2;
4;
8;
16;
32;
64;
128;
256;
For a
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14—4
14.5.2
Error Codes
The error codes reiirned by SPOOL are provided in a TYPE declaration at the beginning of a program.
The TYPE command has the form:
TYPE SPOOLERROR =
(SPOOLED,
NOSPOOLERALLOCATED, BADPRINTERNAME,
OUTOFQUEUEBLOCI(S, FILENOI'FOUND);
14.5.3
Function Definition
Finally, the external, function linkage definition is made as follows:
EXTERNAL FUNCTION SPOOL(F,P: STRING;
SW,CP: INTEGER;
FRM: STRING;
L,W: INTEGER): SPOOLERROR;
14.5.4
The SPOOL Subroutine
Call SPOOL via:
SPOOLCODE:SPOOL(FILENAME,PRINTER,SWITCHES,COPIES,FORMS,LPP,WIDTH); where:
SPOOLCODE
A variable of type SPOOLERROR which gets the completion code shown in the above TYPE declaration.
If SPOOLCODE is not set to SPOOLED after the call is made, then an error of some kind occurred and the file was not printed.
FILENAME
A string variable or expression that gives the specification of the file you want to print.
PRINTER
SWITCHES
A string variable or expression that gives the name of the printer to which you want to send the file.
If
PRINTER is a null, string, SPOOL uses the default printer.
An integer variable or expression that specifies various control switches and flags that affect the printing of the file.
The control switches that SPOOL uses are exactly the same as the switches used by the monitor PRINT command.
the "AMOS System Commands Reference Sheets"
(See in the User's
Information section of the AM—100 documentation packet for information on PRINT.)
Each switch
(see below).
you can use has a numeric code associated with It
For example, the BANNER switch code is
1; the
DELETE switch code is 4.
Set control switches by putting the suni of the appropriate switch codes into the SWITCHES variable.
SYSTEMS FUNCTIONS AND PROCEDURES
COPIES
FORMS
LPP
WIDTH
Page 14—5
For example, if you want to use the BANNER and DELETE switches
(to tell the line printer spooler program to print a banner page and delete the file after printing it), load SWITCHES with
5
(BANNER code
+
DELETE code).
If you set SWITCHES toO (or do not specify one value of a switch pair), SPOOL uses the default switches for the seLected printer.
Switch codes:
BANNER
NOBANNER
DELETE
NODELETE
HEADER
NOHEADER
FF
NOFF
WAIt
1
2
4
8
16
64
18
256
An integer variable or expresion that specifies the number of copies to be printed.
If COPIES is 0, the line printer spooler program prints one copy.
A string variable or expression that specifies the form on which the file is to be printed.
If FORMS is a nuLL string, the tine printer spooler uses the NORMAL form.
An integer variabte or expression that specifies the number of tines per page.
SPOOL only usel this vatue if you have specified the HEADER switch in the SWITCHES, variable.
If you omit LPP, the spooler program uses the default value for the specified printer.
An integer variabLe or expression that specifies the width (In characters) of the print tine (for header printing).
If
WIDTH is 0, the spooter program uses the
4efault vatue for the specified printer.
14.6
XLOCK AND GETLOCKS
XLQCK and GETLOCKS are two assembLy language subroutines that allow setting, clearing, and listing of multi—user file locks, lilce the equivalent BASIC subroutine
XLOCK.
In fact, the locks set by the Pascal XLOCK are the same as those set by the BASIC XLOCK.
This means that Pascal and BASIC programs can be used to Lock each other out.
For a lengthier discussion of the concept of "file locks," refer to FLOcK —
BASIC
Subroutine to Coordinate Multi—user FiLe Access, (DWM—OO100—16), and
LOCK
—
BASIC
Subroutine for
Multi—User,
Locks, (DWM—OO100—11), in the
BASIC Programmer's Information section of the AM—100 documentation packet.
Briefly, however, a tile lock is merely a convenience that allows a program
SYSTEMS
FUNCTIONS AND PROCEDURES
Page 14—6 to check to see if a' current file is in use.
The reason for file
Locks is that muLtiple users..itl destroy the contents of a file if they access it at the same time.
A file Lock heLps programs keep track of whether or not a fiLe is currently being accessed.
The program accessing the file
"sets" a lock on the fiLe to Let other programs know that they must wait.
Then, when the program
Leaves the file, it
"clears" the Lock, making the fiLe accessibLe to other programs.
it is important to stress that a fiLe Lock is not a security device.
MuLtiple programs can access the same file whether or not file Locks.1 are set on that file; however, by checking file Locks, a program can prevent a fiLe from being damaged by refraining from accessing it whiLe another program is using it;
It is not necessary to Load the Pascal XLOCK routine into memory.
However, the routine does require one word of data In system memory to
Link to the system queue list, which contains the locks set by XLOCK
This link Is contained In the fiLe DSKO:XLOCK.SYSfl,4).
This file should be
Loaded into system memory so that XLOCK may work.
If XLOCK.SYS
is not loaded into system memory, then the
AIphaBASIC subroutine XLOCK.SBR must be.
This is because the
AlphaBasic
XLOCK wiLL contain within itseLf a link to the system queue blocks which contain the
Locks set by both XLOCK routines.
documentation.
For more information, see the XLOCK
There is no problem if both XLOCK.$BR and XLOCK.SYS are in system memory at the same time.
The Pascal XLOCK will use XLOCK.SBR, so that BASIC and
Pascal are using the same List of locks.
The lock values defined beLow (LOCKI and LOCK2) are required for each lock.
LOCK1 is called the "MAJOR LOCK" and LOCK2 Is caLLed the "MINOR LOCK."
If a value of 0 is set in either lock, thn that lock becomes a wildcard and matches all values in that position.
For instance, a LOCKI of 3 and a LOCKZ of
0 locks out aLL locks with a LOCK1 of 3.
Any other user that tries to use a LOCKI of 3 will be Locked out,
If LOCKI Is set to 0, then aLt locks wiLt be set.
For more information, see a description of the BASIC XLOCK subroutine.
14.6.1
The XLOCK Subroutine
XLOCK is an external function.
Therefore, It must be specified as such in the Pascal program that uses it:
EXTERNAL FUNCTION XLOCK(MD: XLOCKMODE;
LOCK1 ,LOCKZ: INTEGER): INTEGER;
The type XLOCKNODE is defined as follows:
TYPE
XLOCKMODE =
(SETLOCK,
SETLOCKWAIT, CLEARLOCK)
1
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14—7
(These two declarations can be included ma program by using <SI
XLOCK).)
The result of the XLOCI( call will be returhed in the integer
RETCODE: variable
RETCODE:
XLOCK(MODE,LOCK1 ,LOCK2);
Where
MODE is one of the modes specified in XLOCKMODE, and LOCK1 and LOCK2 are integers containing the locks to be set.
If RETCODE is ever set to —1, this means that a bad mode was passed to
XLOCK.
This can happen if there was an error in setting up XLOCKMODE.
14.6.2
Setting a Lock
A lock is set using
XLOCI( mode SETLOCK.
For instance, if the user had opened a file on channel 3 and was updating record 47, he might enter the following code into his PascaL file:
LOCK1:=3; <locking file 3)
LOCK2:47; <locking record 47)
RETCODE : =XLOCK(SETL.OCK,LOCK1 ,LOCKZ);
If the lock was successful, then RETCODE is set to 0.
If not, the job number of the job that has that Lotk Is returned In RETCODE.
14.6.3
Setting a Lock (and Waiting Until It Is AvailabLe)
It is sometimes necessary to wait for a lock to become cLear.
To do this, mode SETLOCKWAIT is used insteadof SETLO'CK.
This mode, assuming the above example, Is used as tot lows:
RETCODE: =XLOCK (SETLOCKWAIT,LOCK1 ,LOCKZ);
If the lock is held by another user, the program will be put to sleep untiL it becomes available.
When XLOCK returnsto the user program, RETCODE wilt contain a 0 if the lock was allocated, or the user's job number if the lock already was allocated to him.
14.6.4
Clearing a Lock
After a lock is no longer needed (i.e. in the above example, moving to another record) it must be cleared so that other userS have access to that lock.
example:
To clear a lock, the CLEARLOCK mode Is used.
Again, using the above
RETCODE:flLOCK(CLEARLOCK,LOCK1 ,LOCK2)
SYSTEMS FUNCTIONS AND PROCEDURES
Pege 14—8
RETCODE wiLL after the c was cLeared,
LOCKZ and muc contain the number of Locks that aLl, then no Locks were cLeared,
If REtCODE > 1, then a wiLdcard ho Locks were cleared, were cleared,
If RETCODE
If RETCODE = 1, then one was specified in
LOCKI
=0
lock or
14,6,5
The GETLOCKS Subroutine
GETLOCKS is an externaL procedure, in the Pascal program that uses it:
Therefore, it must be specified as such
EXTERNAL PROCEDURE GETLOCKS(VAR
LOCKQTY,JOBNUM: INTEGER;
VAR LOCKARRAY: LARRAY);
Type LARRAY is an array of type LOCK,
LOCK is set up as follows:
TYPE
LOCK = RECORD JOB,LOCK1,LOCK2
:
INTEGER END;
If X is
a variable of type LOCK, then X,JOB is the job number that holds lock,
X,LOCK1 and X,LOCK2 are the lock valued of the lock,
LARRAY defined as follows: the is
TYPE
LARRAY = ARRAY[1,,25] OF LOCK;
The variable LOCKARRAY may then be allocated for GETLOCKS to return the list
of locks in:
VAR LOCKARRAY
:
LARRAY;
Be in sure to set up type LARRAY as an array large enough to number of possible locks on your system, the maximum number of anticipated locks,
Since there is no external procedures or functions, LARRAY must be large
Therefore, it is set LARRAY to the number of queue blocks allocated in your hold the maximum a range checking enough to receive good idea to system,
If
there is a possibility that more than 25 locks may be set at a time when
GETLOCKS (see below)
is called, then it
be increased,
The file DSKO:XLOCK,INC[7,5], which contains the of LARRAY, may be modified, is necessary that the size of LARRAY
definition
To get a list of locks, enter into your program:
GETLOCKS(LOCKQTY,JOBNUM,LOCKARRAy);
Where LOCKOTY is an integer that receives the number of set locks, JOBNUM is an integer that receives your job number, and LOCKARRAY is the array that
receives the list of locks,
.
SYSTEMS FUNCTIONS
AND PROCEDURES
Page 14-9
One thing you might do with this List
of Locks is List it,
FOR LOCKLIST:1 TO LOCKQTY DO
WITH LOCKARRAYELOCKLIST] DO
BEGIN CLIST LOCKS)
VRflELNYJOB =
,JOB);
WRITELNYLOCK1 =
,LOCK1 );
WRITELNVLOCK2 =
,LOCKE);
END; CLIST LOCKS)
To do this:
14,7
XMOUNT
XMOUNT is an assembLy Language routine that allows you to mount a disk from within a PascaL program without Leaving Pascal, you change a
You should call it whenever disk and your Pascal program is going to use that disk,
You must always mount a disk after you have changed it and before you write to it,
Otherwise, the system
will think that the old disk is still in the
drive, and use the old disk°s bitmap to find unused disk blocks,
14,7,1 Error Codes
The error codes returned by XMOUNT are specified in a the beginning of a program, having provided the form:
TYPE declaration at
TYPE MOUNTERROR = (MOUNTED, UNMOUNTED, DEVNOTFOUND, BADHASH, NOVOLID);
Next, some variable to contain the device specification and that
will
variables contain the
will
have volume to be defined,
ID of the newly return an error code in a variable that should be
XMOUNT requires a string another string variable mounted disk,
XMOUNT will of type MOUNTERROR:
VAR DEV,VOLID:
P ETC ODE
STRINGE1O];
MOUNTERROR;
Next, the function (XMOUNT) must be defined as follows
EXTERNAL FUNCTION XMOUNT(D:
VAR V: STRING):
STRING;
MOUNTER ROR;
{$I XMOUNT) will include the required TYPE and EXTERNAL FUNCTION definitions required by XMOUNT,
XMOUNT is then called via:
RETCOOE: =XMOUNT(DEV,VOLID);
SSTENS FUNCTIONS AND PROCEDURES
Page 14—10
Where
0EV
ID, if any.
is a string
DEV:tDSK3:) and
VOLID containing the device to be mount.ed
(e,g,, is the string variable used to receive the volume
14,7,2
Unmounting a Disk
A disk may be unmounted by specifying
VU'
RETCODE:XMOUNT('DSK23:/u',VOLID);), after the
0EV spec
(i,e,
If a disk is to be unmounted, the '/U' must contain an upper case 'U',
When you unmount a disk, you prevent
BASIC and most system programs from being able to access that device.
Note that
VOLID is incLuded, even though it is not needed because a volume id is not returned when a disk is unmounted,
VOLID is required at all times,
14,7,3
Error Codes
The error (or return) codes specified above have the following meanings:
14,7,3,1
MOUNTED
The device was successfully mounted and the volume ID is in VOLID (or whatever the second string was called),
14,7,3,2
UNMOUNTED
The device was unchanged, successfully unmounted,
VOLID is
14,7,3,3
DEVNOTFOUND "
The specified device was not defined at system generation, and is not in the system device table,
VOLID is unchanged
14J,3,4
BADEIASH " The device was mounted, but
it
was a storage module device with a BADBLK,SYS,
When the new BADBLK,SYS was read, it was found to contain a bad hash total,
VOLID is unchanged,
14,7,3,5
NOVOLID The disk was successfully mounted, but there was no volume ID on the disk,
Note that MOUNTED and
NOVOLID specify successfuL mounting of the disk,
UNMOUNT specifies a successful UNMOUNT, and BAN-lASH indicate errors occurred while attempting
DEVNOTFOUND to mount the disk, either of these errors occur, you should not try to access that device!
If
,
S
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14—11
14.8
TIME
The TIME procedure places the contents of the system clock Into the two specified variables.
(The system clock contents increment every sixtieth of a second on most systems, and every fiftieth of a second on other systs; the actual amount is specified by CLKFRQ in SYSIEM.INI.) Wordl contains the most significant part of the returned valul, Wordi and Word? must be declared INTEGER variables.
The procedure lnvoéátion takes this form:
TINE(Wordl ,Word2);
For example:
PROGRAM TestTime;
VAR First,Second
:
INTEGER;
BEGIN { TestTime )
TIME(Fi rst,Second);
WRITELN('The time is: ',First,',',Second)
END C TestTime ).
When the program above was run at 5:30:02 Ptl, It printed:
The time is: 56,2086
NOTE: Because the clock contents are stored as a
32—bit unsigned value,
Word?
may sometimes be interpreted and negative number.
displayed by the computer as a
14.9
TOO
TOO takes no arguments, and returns a
real
number corresponding to the nuaber of seconds since midnight, according to tht time of day.
Internally, the time of day is converted from a two word integer to a real number, and then divided by the clock frequency defined in SYSTEM.INI.
Therefore, the resolution on 60 cycle systems is to within .01666... seconds, and on 50 cycle systems is to within .02 seconds.
You will probably find TOO to be of most use for timing purposes or for calculating the time of day.
SYSTEMS FUNCTIONS AND PROCEDURES Page l4-l2
14,10
ERROR HANDLING PROCEDURES AND VARIABLES
Whenever an a as resuming error occurs, the
AiphaPascal message (incLuding the Location of the error) and aborts to AMOS.
Whenever user types a
Control"C whiLe his suspended and the user is aLlowed to choose among a series of options such his program, exiting to system prints an appropriate program is executing, execution is
AMOS, or dispLaying a hacktrace of suspended functiOn and procedure invocations,
However, it is not always desirabLe to Let the system perform error handling for you.
You may wish to alLow the user to type a
Control"C in order to exit from some mode of a program, or in order to obtain a status report on the progress of your program in processing some task,
II: may be that you have an applications package in which the users of your package are unfamilar with AMOS,,, if an error occurs you may simply wish to message and return to the top level of your applications package, print be
Or it may that you enforce security on your system, and have an unattended program that you wish to LOGOFF automatically if an error occurs, a
For own you with these reasons and more, it is desirable for you to he able to write your routine to handle a Control"C and error conditions,
AlphaPascal allows to do so, and the remainder of this section will attempt to provide you the necessary information to write such a routine,
141O,1
Including ERT,INC
In order to write your own error routine, you must include a special set of definitions with {$I ERT),
Doing so includes the following text:
TYPE
"TN'FOREC
RECORD
XEQERR:
INTEGER;
F ILERC: INTEGER;
ERRFIB: 'TEXT;
{Additional information for internal use only)'
END;
EXTERNAL PROCEDURE XERRORTRAP(VAR INFO: INFOREC);
EXTERNAL PROCEDURE STDERRORTRAP;
14,10,2
ERRORTRAP
To catch errors, you must write a global procedure of no arguments with the name ERRORTRAP,
Here is a very simple example of such a procedure:
SYSTEMS FUNCTIONS AND PROCEDURES Page 14'13
PROCEDURE ERRORTRAP;
BEGIN
STDERRORTRAP;
END;
In this exampLe, we simpLy call the standard system error handler
STDERRORTRAP,
In order to determine the nature of the error which has
Tioked eFF5rtrap, you must use the function ERRORINFO in conjunction with a variable declared as type INFOREC:
PROCEDURE ERRORTRAP;
VrINFOP: "INFOREC;
BEGIN
INFOP
:
ERRORINFO;
WRITELNV?Error ',INFOP'J(EQERR);
STDERRORTRAP;
END;
In this example, we also display the error code corresponding to the error which occurred before calling the standard error handler, codes is as follows;
The list of error
Error
Code
Meaning
3
4
5
6
7
S
10
11
12
13
14
15
16
17
18
19
20
21
22
23
Value range error
Exit from uncalled procedure
Memory capacity exceeded
Integer overflow
Divide by zero
Bad pointer reference
(ControHc)
(I/O error)
Unimplemented runtime instruction
Floating point error
String overflow
Programmed HALT
Programmed breakpoint
ARCSIN(x) or ARCCOS(x) where abs(x)
LOG(x) or LN(x) where x <= 0
SQRT(x) where x < 0
TAN(PI/2 +
ARCCOSH(X)
>1 k*PI) is undefined for integer k (bad TAN argument) where x
<
1
FACTORIAL(x
ARCTANH(x)
POWER(x,y) where x is a negative integer where abs(x)
>
1 where x
< 0 and y is a fraction
In the case of I/O errors, there is some additional information, namely the
type of error and the file involved, which is available:
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14—14
PROCEDURE ERRORTRAP;
VAR
INFOP:.flNFQREC;
BADFILEP:
TEXT;
IP4FOP
:
ERRORINFO;
IF INFOr.XEQERR = io cl/a Error)
THEN
'BEGIN
BADFILEP
XNFOP .ERRFIP;
WRITE('?I/O error ',INFOP.FILERC,' has occurred in ');
PFILEtBADFXLEV);
WR1IJELN;
END;
STDERRQRTRAP;
END;
In the above example, if an I/O error has occurted, we display the file error code (INFOP..FILERC) and the name of the file involved
(INFOP.ERRFIB).
ERRFIB is a pointer to the most recently processed file, which
Is why we first save It in BADFILEP before writing to the terminal, otherwise our message would read
?I/O error xxx has occurred in TTY: regardless of the actual file in which the error occurred.
Here is a list of the I/O error codes.
They are the standard codes used by
AMOS:
I/O
Error
Code Meaning
1
2
3
4
$
9
10
11
12
13
S
6
7
14
15
16
17
18
19
20
File specification error
Insufficient
free memory for INH
File not found
File already exists
Device not ready
Device full
Device error
Device in use
Illegal user code
Protection violation
Write protected
File type mismatch
Device does not exist
Illegal block number
Buffer not INITed
File not open
File already open
Bitmap kaput
Device not mounted
Invalid filename
In the examples so far, we have always been calling STDERRORTRAP to handle our errors.
STDERRORTRAP always aborts to AMOS without returning with the
4
SYSTEMS FUNCTIONS AND PROCEDURES
Page 141S exception of a
ControHC followed by a command to resume,
Thus the
ERRORTRAP procedures themseLves have aborted to AMOS in most circtsnstances,
In addition STDERRORTRAP resets INFOP',XEOERR to zero before execution is to be resumed, error handler executing an itseLf for
This is because errors MUST NOT occur in the obvious reasons, AiphaPascal error handler whenever XEQERR is nonzero, occur within an error handier, the message returning assumes
it
if is
If an error does
?Attempt to calL ERRORTRAP while in ERRORTRAP is displayed, a direct abort to AMOS is made without closing any open files.
Thus, by reseting XEQERR to zero, STDERRORTRAP signals to
AlphaPascal that error handling is finished and further errors are again acceptable,
Should you decide not to call STDERRORTRAP at all, please keep in mind the following points:
1,
The only errors from which you may safely resume execution are S
(a
ControHC) and 10 (I/O error),
An attempt to resume execution by returning from ERRORTRAP with any other errors will probably crash the system,
2,
It
is acceptable to use EXIT to abort some function or procedure,
or 7our
program, when any error occurs, Of course you can only
EXIT to leave a function or procedure which is currently active, so you will probably want to have around some BOOLEAN variables to keep track of whether or not you are currently within routines which you might wish to EXIT from ERRORTRAP,
3.
Remember to set XEOERR back otherwise your next error
ER RO PT P A P to zero before leaving
ERRORTRAP,
will
abort to
AMOS without calling
14,10,3
XERRORTRAP
When STDERRORTRAP is called by entering a request a
Control"C, backtrace of suspended functions and procedures
This backtrace begins with the caller of the caller of STDERRORTRAP, which is usually the caller of
ERRORTRAP, and hence the routine which was suspended
Thus, should STDERRORTRAP be called by a
ERRORTRAP as its argument,
It it
is possible procedure, the backtrace will begin in the wrong place, to function or procedure local to your is used as follows:
This can he corrected by using XERRORTRAP, which takes a copy of the system
INFOPEC
(changed 30 April 1981)
SYSTEMS FUNCTIONS AND PROCEDURES
S
Page 14—16
PROCEDURE ERRORTRAP;
VAR iNrop: aINFOREC; INFO:
INFOREC;
PROCEDURE P1;
BEGIN
XERRORTRAP(INFO);
END;
BEGIN
INFOP :=
ERRORINFO;
INFO :
INror;
P1;
INFOP,XEQERR
:
INFO.XEQERR;
END;
Using
XERRORTRAP, the backtrace will be disptayed beginning with the catler of the routine which Invokes ERRORINFO, thus producing a correct even when calLed from an
Inner procedure.
backtrace,
Begin at the caller of the procedure which set X to ERRORINFO.
14.10.4
ERROR
The procedure ERROR(x) takes an INTEGER x as argument and generates the corresponding system error.
See the previous section for the list of error codes.
S
.
(changed
30 April 1981)
SYSTEMS FUNCTtONS AND PROCEDURES
Page 14—15 exception of a
Control—C followed by a command to resume,
Thus the
ERRORTRAP procedures themselves have aborted to AMOS In most circumstances.
In addition1 STDERRORTRAP resets INFOP .XEQERR to zero before returning if execution is to be resumed.
This is because, errors MUST NOT occur in the error handler itself for obvious reasons.
AtphaPascal assumes it is executing an error handler whenever XEQERR is nonzero.
If an occur does occur within an error handler, the message
?Attempt to call ERRORTRAP while in ERRORTRAP is displayed, a direct abort to AMOS is made without closing any open files.
Thus, by reseting XEQERR to zero, STDERRORTRAP signals to
AlphaPascal that error handling is finished and further errors are again acceptable.
Should you decide not to call STDERRORTRAP at all, please keep in mind the following points:
1.
The only errors from which you may safely resume execution are B (a
Control—C) and 10 (I/O error).
An attempt to resume execution by returning from ERRORTRAP with any other errors will probably crash the system.
2.
It is acceptable to use EXIT to abort some function or procedure, or your program, when any error occurs.
Of course you can only
EXIT to leave a function or procedure which is currently active, so you will probably want to have around some
BOOLEAN variables to keep track of whether or not you are currently within routines which you might wish to EXIT from ERRORTRAP.
3.
Remember to set XEQERR back to zero before leaving ERRORTRAP, otherwise your next error wilt abort to
ERRORTRAP.
AMOS without calling
14.10.3
XERRORTRAP
When STDERRORTRAP is called by entering a
Control—C, it is possible to request a backtrace of suspended functions and procedures.
This backtrace begins with the caller of the caller of STDERRORTRAP, which is usually the caller of
ERRORTRAP, and hence the routine which was suspended.
Thus, should STDERRORTRAP be called by a function or procedure local to your
ERRORTRAP procedure, the backtrace wilt begin in the wrong place.
This can be corrected by using XERRORTRAP, which takes a copy of the system INFOREC as its argument.
It is used as follows:
SYSTEMS FUNCTIONS AND PROCEDURES
Page 14l6
PROCEDURE ERRORTRAP;
VKR fKWOp: INFOREC; INFO: INFOREC;
PROCEDURE P1;
BEGIN
XERRORTRAP(INFO);
END;
BEGIN
INFOP
:
ERRORINFO;
INFO
INFOP'
P1;
INFOP ,XEQERR
:
END;
INFOXEQERR;
Using
XERRORTRAP, the backtrace wiLL be dispLayed beginning with the caLLer of the routine which invokes ERRORINFO, thus producing a correct even when caLled from an inner procedure, procedure which set
X to ERRORINFO, backtrace,
Begin at the caLLer of the
14AO,4
ERROR
The procedure ERROR(x) takes an INTEGER x as argument and generates the corresponding codes, system error,
See the previous section for the list of error
.
CHAPTER 15
ASSEMBLY LANGUAGE SUBROUTINES
Assembly Language subroutines are assembLy Language programs caLlabLe by your ALphaPascaL programs, that are
Why would you want program?
There are at capabilities of the operating system (AMOS) have been directly included in
AlphaPascaL.
to enrich
ALphaPascaL, to least two good reasons, as call assembly need languages requires, routines from a Pascal
Firstly,
not
all
The ability to write assembly language subroutines allows the
with additional capabilities,
SecondLy, routines written in assembLy Language execute significantly faster than routines written in
PascaL, Thus, you may wish to
identify
you key functions and procedures which are bottLe necks in your programs, and rewrite them in assembly Language.
This chapter describes how to write and use assembly
Language subroutines,
It
wiLL be assumed in this chapter that you are an experienced assembLy
Language programmer on the AMOS system,
For more
Language programming, pLease refer to the information on assembLy
AMOS
AssembLy Language
Programmers Reference
ManuaL (DWM"OO1OO43), the
WD16
Microcomputer
ManuaL (DWM"OO100"04), and the AMOS Monitor CaLLs ManuaL (DWM-OO1OO—42),
15,1
CALLING ASSEMBLY LANGUAGE SUBROUTINES
In AiphaPascai, there is no distinction between calling an assembly Language function or procedure, and caLLing a Pascal function or procedure which occurs in a separately compiled moduLe, (ModuLes were discussed in
Section
5,1,)
Section 4,4,4 describes how to Link an assembly Language subroutine into a program during the PLINK process,
Instead of Linking output fiLes from the compiler, you link a
PRG file with an extension of ,PSB which contains code for a single function or procedure,
The name of the PSB must be the
first
six assembLy Language routine, course,
Letters of the file name to be used for calling the
When specifying the fiLe to PLINK you must, of specify the fuLl name of the procedure or function contained in the
P38 fiLe, otherwise PLINK wouLd not know the fuLL name you wish to use for
it,
ASSEMBLY LANGUAGE SUBROUTINES Page 152
For example, if you code in assembly language a procedure that displays a menu, the procedure name might he MENUDISP, routine must then., be called MENUDI, though, you use the
full
When you specify the file to PLINK, eight--character
The disk file
name of the containing procedure, that
For example:
File
1
= MENUDISP, PSB/LINK
15,2
ARGUMENT PASSING CONVENTIONS
Your assembly language routine must work with two stacks,
One of these stacks is the familar
SP stack.
The other is a data stack used by
AlphaPascal for passing arguments and recieving results,
The data stack is indexed by P5, and so will also be referred to as the P5 stack, All other registers (RO"R4) are avai lable for any purpose to your assembly routine,
Arguments are placed on the RS stack in reverse order, argument appears on the top of the R5 stack, following program in AlphaPascal:
That is, the last
For example, if we have the
File TEST1,PAS"
PROGRAM;
EXTERNAL
BEGIN
PROCEDURE demol (x,y: INTEGER); demol (10,20);
END,
then,
upon entry to our assembly language subroutine, 20 will be on the top of the PS stack (referenced as BR5) and 10 will be under it on the PS stack
(referenced as 2(R5)),
A procedure
DEMO1 ,MAC: to print
its
two
INTEGER arguments in order might then be
File
DEMO1,MAC"
COPY SYS
START:
MOV
DCVT
CRLF
MOV
DCVT
CRLF
ADDI
RTN
2(R5),R1
0,2
&R5,R1
0,2
4,R5
;
;
;
;
;
;
Get first argument
Print it in decimal
Get second argument
Print it
in decimal
Remove arguments from R5 stack
Return to pascal
DEMO1 would then be assembled with MACRO, and the
DEMO1,PRG would he into a code tile by PLINK, resulting program tile renamed to DEMO1,PSB in order to allow it to be linked
ASSEMBLY LANGUAGE SUBROUTINES
Page 153
When caLled as a function rather than as a procedure, your routine will receive an additionaL three words containing zeros on the top of the R5 stack, be
These words serve no purpose when writing assembly routines and may immediately removed by executing an ADDI
ó,R5,
Their presence is required for internal reasons by functions written in Pascal.
Assembly language functions return their result on the top of the
R5 stack after all arguments have been removed,
Example:
File TEST2,PAS—
PROGRAM;
EXTERNAL FUNCTION Maximum(x,y: INTEGER): INTEGER;
BEGIN
WRITELN (Maximum (2,7));
END,
File MAXIMU,MAC"
START: ADDI
MOV
MOV
CMP
BHI
MOV
R TN
USE1SI: MOV
R TN
6,R5
(R5)+,R2
(R5)+,R1
R1,R2
USE1ST
R2,(R5)
R1,"(RS)
;
;
;
;
;
;
Throw away unused additional words
Get 2nd argument
Get 1st argument
1st >
2nd
2
Yes, return 1st argument
No, return 2nd argument
;
Return 1st argument
After producing MAXIMU,PSB, you would need to remember to refer to the file as MAXIMUM,PSB to
PLINK, otherwise it would think the function being defined hid the name Maximu instead of taximum,
15,2,1 Argument passing
There are two methods of passing arguments in Pascal, typified by:
1, and
2.
PROCEDURE(x: INTEGER);
PROCEDURE(VAR x:
INTEGER);
In the first declaration, x is referred to as a value parameter, In the second declaration, x is referred to as a reference parameter.
In general, value parameters appear directly on the
R5 stack, while reference parameters (denoting variables which can be modified) appear as an address on the R5 stack which points to the parameter,
However, there are exceptions: arrays, records, and strings always have their address passed on the
R5 stack, even when they appear as value parameters,
ASSEMBLY LANGUAGE SUBROUTINES
Page 15"4
15,2,2
Data Formats.
This section describes the internaL format of each data type, types are aLigned on a word boundary unless contained as
ALL data a packed field,
15,2,2,1
CHAR - Characters are represented •by their
ASCII code in machine word,
They are only a fulL stored within single bytes of memory when contained in packed arrays or records,
15,2,2,2
INTEGER
Integers are represented in a single machine word,
15,2,2,3
(TRUE)
BOOLEAN " Booleans are
in'j full
machine word, represented contained in packed arrays or records, by a zero
(FALSE) or one
They are onLy stored as single bits when
15,2,2,4
Subranges and Scalar types
These are represented in machine word unless they appear in a
full
a packed array or record, in which case
they are stored in a field of as
many bits as necessary to hold their maximum value, User scalar types are numbered starting from zero,
15,2,2,5
REAL
Reals occupy three words of memory and conform wtth the format for reals used by the
FArm,
FSUB,
FMUL,
FDIV, and
FCMP machine instructions,
15,2,2,6
STRING —
Strings are represented by a length byte containing
O"255, foLlowed by a sequence of bytes which are used to hoLd the actual characters of the string,
15,2,2,7
Pointers " Pointers require a full machine word,
15,2,2,8
Sets "
Sets require one or more words depending upon the size of the set,
Sets are represented as a bit pattern, where a one bit denotes the presence of a set element, order in
The bits are ordered from low order to higher each word, and from first word to last word,
For example, SET OF
3,,19 requires two words of memory, thru 2 are unused,
The first three bits corresponding to 0
To test for the presence of the element
18, one would perform a bit test on the second word of the set with a mask of 4,
ASSEMBLY LANGUAGE SUBROUTINES
Page 15—5
15.2.2.9
Arrays —
Arrays require one or more, words.
the elements of an array appearS in order in memory.
In packed arrays, the eLements of an array may each occupy on a few bits, otherwise each element, fr411.t appear on a word boundary.
Fields appear from low order to high order, in a word,, and may not cross word boundaries.
15.2.2.10
Records —
Records require one or mr# words.
The elements of a record appear in order in memory In a fashion simi tar to arrays.
15.2.2.11
Files —
The
Files are actually an internal 'kind of record format.
details of this format are not being made available as they will change as versions of AlphaPascal change.
15.2.3
Error Exit
Should 'you wish to generate an error from your assembLy language subroutine, it is preferable that you calL the Pascal' systern's
ERRORTRAP procedure, rather than display an error and exit to AMOS directly, Otherwise there Is no guarantee that open files will be close4 côrreptty.
To signal an error, you must perform a prop!r return from your routine, but
In addition, advance your return address by ex'ec*i4lng 1W2 SSP, and Leave an execution error code in RI.
For additional information on ERRORTRAP and a
List of execution error codes, see section 14.10, "Error Handling Procedures and Variabtes.'
15.3
CODE RESIDENCY
This section discusses the variety of ways In which your routine may appear in memory.
15.3.1
Routines PLINKed with /LINK
Routines which have been linked into a code file with the /LINK option must have a final P58 file which is exactly one block in size.
Such routines are dynamically paged into memory along with
Pascal psuedo—code.
They are deleted from memory and reloaded as memory requirements and usage demand.
They place no burden on available memory when not being used.
ASSEMBLY LANGUAGE SUBROUTINES
Page 15—6
15.3.2
Routines PLINKed without /LINK
Routines which have been linked into a code file without the /LINK option will be searched for in memory and on disk each time they are called.
What has been linked into the code file is not the actual routine, but rather the name of the PSB file containing that routine (see section 4.4.4).
If your routine has been loaded before. entering AlphaPascal via the LOAD command, either intq system memory r user memory, then that copy of your routine wilt be used.
If your routine is not present in memory, it wilt be temporarily loaded in order for it to be executed, and then deleted from memory immediately after execution.
15.4
OBTAINING MEMORY FOR DATA AREAS
When writing an assembly language routine, you will, probably want and need temporary data area$.
There is rio room for allocating memory modules for this purpose.
Instead, you may either allocate space for data in the SR stack, or place your data inline in your routine (this is unacceptable for routines which are to be loaded into system memory, since they must be sharabte).
The R5 stack is NOT available for allocating data space.
Another method for obtaining larger data areas, is to have your caller pass them to you as arguments.
15.5
RESTRICTIONS
As mentioned above, there is no room for allocating memory modules.
This also means that you may not use INIT to create a file buffer, or perform file operations which would require loading a device driver Into memory.
.
CHAPTER 16
WRITING AND MODIFYING AN EXTERNAL
LIBRARY
When you link together your programs using PLINK, you are asked to specify a library file.
Typically, ybu specify siuctS;'
The global functions, procedures, and variables crttaihed in thts" Library are available to you just as if you wrote them in a modute and linked them into your program.
However, using routines contatned in a library requires no additional space in your program's code file because the routines are accessed directly from the library file at run—time.
There are several advantages to placing commonly used routines in a library rather than linking them directly into your Program.
First, you save disk space by only having a single copy of yOur i'otatlnes on disk,
Second, the linking process is faster if yu only need to spetify a library rather than several files contain your modules.
Finally, if It becomes necessary to modify a routine, you need only change it iii the'lJbrary to update alt your programs which use it.
Another a program.
possible use of libraries is to genere, multiple configurations of
A single program could be lInked to a variety of Libraries each of which define the same set of functions and procedures, but each of which do so with different definitions.
This mightl be used to configure a generalized set of applications programs for uSe in different specific applications.
It is not necessary to specify
EXTERNAL declarations for most of the functions and procedures in
StDLIB.
ThIs is NoT a feature of libraries.
Rather, the compiler has been written to', automtttcatly include EXTERNAL declarations for these commonly uled routines.,
There is really very little difference between a program file and a library file.
Both are actually AlphaPascäl. programs.
The only difference is that if
Program
A uses Program B as a library, then Program B is executed with the purpose of initializing the library
(i.e.,: global variables in the library), before Program A is executed.
It is possible for a library to itself hay! a Library.
Thus Program A can use Program B as a library, and Program B can use Program C as a library, in which case C, then B, and finally A are executed.
WRITING AND MODIFYING AN EXTERNAL LJBRARY
Page 16—2
To allow programs to be written which can serve either directly as program, or indirecy as a Library, a special BOOLEAN function is provided, called MAINPROG, which takes no arguments and returns true if the program in which
It Is executing is being used as the main program, and false if the a program in which it is executing Is being used as a library to another program.
The idea is to write a program in such a way that if it is being used as a library, all it does is initialize global variables.
16.1
STDLIB
STDLIB is a special Library which itself has no, library.
basic set of mandatory procedure and funétion
It provides a definitions.
It is permissable for you to overide any of these definitions with your wn external procedures or functions with the exception of RDC, RDI, RDR, RDS,
RLN, WLN, WRE, WRC, WRI, WRR, and WRS.
Calls to these procedures are automatically generated whenever you use READ and WRITE statements.
READ and WRITE will seriously malfunction If you redefine any of these.
The functions and procedures included in STDLXB are:
ARCCOS
ARCCOSH
ARC$IN
ARCSINH
ARCTAN
ARCTANH
CONCAT
COPY
COS
COSH
DELETE
ERRORTRAP
EXP
FACTORIAL
GETFILE
GETLOCKS
INCHARMODE
INSERT
KILCMD
LCS
LN
LOG
OPEN
POS
POWER
PROGRAM
PWROFTWO
RDC
RDI
RDR
RDS
Arc cosine function
Hyperbolic arc cosine function
Arc sine function
Hyperbolic arc sine function
Arc tangent function
Hyperbolic arc tangent function
Function to concatenate strings
Function to copy characters in string
Cosine function
Hyperbolic cosine function
Procedure to delete characters in string
Default error handler
Function to compute e to the specified power.
Factorial function CX!)
Procedure to get information in filespec
Procedure to read file locks.
Returns true if terminal is In Charmode.
Procedure to insert characters into a string
Procedure to abort command file
Function to convert upper case characters to lower case
Function to compute natural (Napierlan) log
Function to compute log base ten of argument
Procedure to open an AMOS file
Function to compute position of character in string
POWERCx,y) computes x to the y'th power
STDLIB initialization
Function to compute powers of two
Routine used by READ
Routine used by READ
Routine used by READ
Routine used by READ
WRITING AND MODIFYING AN EXTERNAL LIBRARY
RESET
REWRITE
RLN
SETFILE
SIN
SINH
TOD
UCS
WLN
WRB
WRC
WRI
WRR
Sn.
SPOOL
STDERRORTRAP
STRIP
SQRT
TAN
TANH
WRS
XERRORTRAP
XLOCK
XMNT
XMOUNT
Page 16—3
Procedure to close a file, and then open for input
Procedure to close, erase, and then open a file for output
Routine used by READ
Procedure to place file information in fitespec
Sine function
Hyperbolic sine function
Routine used by SPOOL; must not be called directly
Procedure to spool files to tine printer
Standard error handler
Procedure to strip trailing blanks from string
Square root function
Tangent function
Hyperbolic tangent function
Returns time of day in seconds as a real nianber
Procedure to convert upper case characters to lower case
Routine used by WRITE
Routine used by
WRITE
Routine used by WRITE
Routine used by WRiTE
Routine used by WRITE
Routine used by WRITE
Special version of error handler.
Procedure to set or release, tile, Locks
Routine used by XMOUNI; must not be called directly
Procedure to mount a disk
16.2
WRITING LIBRARY FILES
It is not
likely
that you would want to dispense with the standard Library file altogether, since the compiler relies on the presence of many of the procedures and routines in that library.
If you did not use
STDLIB, you would have to duplicate for yourself all of the routines listed above that make up that library.
However, it is possible for one library to make use of another.
For example, suppose you want to write your own Library which contains a set of functions that are particularly useful for, the programs that you write
(e.g., you need a set of routines that construct and,dhptay screen menus), you can write such a Library; then, when you link it, you can specify the
STDLIB external library as its library file.,
(The only time you ever Link a file without specifying aTibrary, is when you are linking a root library', such as STDLIB itself—— a very rare occurrence.) In this case, your library file (perhaps named NEWLIB) would be linked with
SIDLIB.
then, when you
Link a new program, you might link It with the: NEWLIB Library.
Your new program would thus be linked with NEWLIB which in'turn has its own Library,
STDLIB.
There is no limit to Library nesting.
WRITING AND MODIFYING AN EXTERNAL I4BRARY
Page 16—4
There are several library: things you shQutd keep in mind when writing an external
1.
If an external procedure or function is declared both in a program and in a library which it uses, then the definition within the program is in effect white execution resides in the program, and the definitions within its libraries are in effect white in its
Libraries.
2.
If you char9e a procedure from pascal to assembly language, or from assembly language to pascal, It is wise to re—create (re—link) that program and all the programs which use it as a library.
references to
Any the procedure which are not re—linked will treat it as the wrong kind of code.
3.
SimIlarly, if while updating a program, you overlde a definition in a library which was formerly accessible, there is no garauntee that all references to the definition will be updated unless you re—link the program and alt the programs which use it as a library.
4.
If a library is updated with PLINK, it is not necessary to update the programs which use that library.
However, if the library must be completely re—created, all programs which use that library will need to be re—created.
Thus, It is desirable to avoid the need to re—create a library.
PLINK does not allow you to enlarge the size of global variables with an update, thus it is wise to avoid having global variables which you may wish to enlarge, such as records, strings, or arrays.
points
Instead use a global pointer variable which the desired object In this way, if you change the size of the object, no global variable will change size.
16.3
MODIFYING STDLIB
If you decide to modify STDLIB, you must do so very carefully.
Because
PLINK uses STDLIB while it is working, you must not directly modify STDLLB.
If you want to add routines to STDLIB, use the AMOS COPYcommand to make a duplicate of STDLIB under another name.
Then, add your routines to the copy of STDLIB using PLINK.
Finally, rename your copy to STDLIB (making sure to keep a copy of the old STDLIB somewhere In case of emergencies).
However, it is far wiser to create a library which has
SIDLIB as its library, rather than to directly modify STDLIB.
Otherwise, when Alpha Micro releases an update to STDLIB, all your programs will need to be re—linked!
.
WRITING AND MODIFYING AN EXTERNAL LIBRARY
Page 16—5
16.4
VERSION CHECKING
Both
PLINK, and
PRLJN check to insure that a program is only given its original library or an update of that file, since, an attempt to use any other file as a Library results in a system crash.
If you attempt to execute a receive the error program with an improper library, you will
?Wrong version of xxx for use with yyy where xxx is the name of your program and yyy is the rame of
Its Library.
If you get this message, it either means that you are. running with an out of date version of Library yyy, or that you are running with a newer version of
Library yyy which had to be re—created.
In the latter case, you wiLl need to re—create your program with PLINK.
S
S
PART Iv
APPENDICES
APPENDIX A
QUICK REFERENCE TO ALPHA PASCAL
This appendix gives a quick summary of the Pascal language as implemented by
Alpha Micro.
For information on a particular Pascal statement or element, look in the index to see what pages of this book contain information on that element.
For a complete description of the standard Pascal language, see
Jensen and Wirth, The Pascal User Manual and ReportS
For a list
of
Identifiers" all
standard
identifiers,
see
Section
5,42,
"Standard
A1
PROGRAM STRUCTURE
A program consists of a heading and a block, and it concludes with a period:
Heading
Block,
The heading takes this form:
PROGRAM program"name; or;
PRO GRAM;
A block has the form: label declaration constant definitions type definitions variable declarations external declarations procedure and function declarations
BEGIN statementi
; statement2 ; , ,,
; statementN END,
It a tile is not a main program file, the heading takes the form;
QUICK REFERENCE TO ALPHA PASCAL
MODULE module-name; or:
MODULE; and the bLock takes the form:
Label decLaration constant definitions type defirtttions variable declarations external declarations procedure and function declarations
Page A2
Ad
DECLARATIONS AND DEFINITIONS
Pascal requires that you define and declare program or procedure
all
variables,
Labels, constants, data types, procedures, and functions at the front of each
Ad1
Label Declarations
Labels are always unsigned integers.
LABEL integerl, integer2
A label declaration takes the form: integerN ;
Add Constant Definitions
CONST
identifierl = valuel;
identifier2 = vaLue?; identifierN = valueN;
Ad3 Type Definitions
TYPE
identifierl
= typel;
identifier2 = (identifier3, identifier4,
identifierS = vaLueL value2;
F
QUICK REFERENCE TO ALPHA PASCAL
A24 Variable Declarations
VAR
identifier identifier
p
, identifier
: data—type;
., identifier
: value1value2;
Ad5 Procedure Declarations
PROCEDURE procedure—name; or:
PROCEDURE procedure—name(formal—parametersl; block; where formal—parameters have the form:
identifierl , identifierN
: typel or:
VAR identifierl
, identifierN
: typel formal—parametersN);
A6 Function Declarations
FUNCTION function—name
: block; result—type; or:
FUNCTION function—name(formal—parametersl;
Jormal—parametersN)
: result—type; b i o c where formal—parameters have the form:
identifierl
, identifierN
: typel or:
VAR identifierl
, identifierN
: typel
Page A—3
Q1JICK REFERENCE TO ALPHA
PASCAL
Page A"4
A,3
DATA TYPES
The data type tells Pascal what range of values the declared assume and what operations may be carried out on those types are simple data types or structured data types.
variable may variables.
Data
A,3,1
Simple Data Types
built,
The simple data type is called a "scalar type," contains a set of elements, and those elements are ordered,
Such a type
A3,1,1
Standard Data Types " The standard data types are:
INTEGER " A non'fractional number in the range "32767 through 32767,
REAL
A floating point number significant to
11 integer values)
1 E37,
digits
(12 for with an exponent range of roughly 1E"37 to
EiOOLEAN " The standard scalar type (FALSE, TRUE),
CHAR
A single ASCII character,
A,3, 1,2 User"defined Scalar Types " A scalar data type takes the form:
(identifier"elementl, identifier"element2,,
, ,identifier'elementN) or a subrange type (of another, already defined scalar type) of the form: first"element
,,
last"element
A,32
Structured Data Types
Simple data types can be organized types, into larger units, called structured
A type definition or variable declaration of a structured data type that includes the keyword PACKED tells the compiler to minimize internal storage for that data type (at the possible expense of execution time),
For example, instead of:
VAR LongLine
:
ARRAY [1,1OOOJ OF CHAR; you could cause LongLine to be a packed array by saying:
VAR LongLine
:
PACKED ARRAY E1,1OOOJ OF CHAR;
QUICK REFERENCE TO ALPHA PASCAL
The structured data types are:
Page A"S
A321
STRING STRING data is a group of characters,
You may optionally specify a maximum length by following the keyword
STRING with square brackets enclosing the number (eg,, STRINGE23J),
A,3,2,2
Arrays
ARRAY [index1type, index2"type,
, indexN—type OF component"type
A,3,2,3
Sets
SET OF elementtype
A,3,2,4 File Type
FILE OF element-type or:
TEXT
(This is the same as "FILE OF CHAR")
A32,5
Record Type
RECORD fieldlist END
where field list is of the form:
fieid—identifier field—identifier
,,, fieLd"identifierN
:
fieLdl"typel;
, field"identifierN
: field2"typeE;
fieidHdentifier
,,, field—identifierN
: fieldN"typeN;
The form:
field
list
may also contain a variant"part, which implies that the information in that fieLd may vary as to type The variantpart takes this
QUICK REFERENCE TO ALPHA PASCAL
CASE field—type OF case—Label
.., case—Label
.., case—label
:
(field—listi); case—label
(field—tist2);
:case.4abel
.., case—label
(field—ListN) or:
CASE case—field—identifier case—label
•.,
: case—label field—type OF
:
(field—listi); case—Label
.., case—label
(fietd—list2);
0Se case—label
.., case—Label
:
(field—listN)
Page A—6
A.3.2.6
Pointer
Data Types —
The pointer enables Pascal to permit dynamic data structures by giving you a way to point to an eLement of such a structure.
It takes the form: obj ect—type
Pascal provides a standard constant NIL, which points to "nothing."
A.4
EXPRESSIONS
Expressions use operators to combine variabl.es, constants, and function calls into larger units.
This section gives tnforrnat ion about each of these components of an expression.
A.4.1
Operators
Operators have precedence, which you can override by Incuding parentheses in the expression.
The unary operators are performed before alt other operators; next the multiplying operators are performed, followed by the adding operators.
the Boolean
Then, the relational operators are performed.
LastLy, operators are applied. If several opàrators in an expression have the same precedence, execution is performed from left to right.
A.4.1.1
Assignment —
QUICK REFERENCE TO ALPHA PASCAL
A41L1 .Lhe Modifying
Assignment Operators
The modifying assignment operators are:
Addition
Subtraction
MuLtipLication
Division
A4L2 Arithmetic Operators:
+
+
*
I
DIV
MOD
(unary operator) Identity
(unary operator) Sign inversion
Addition
Subtraction
Multiplication
Integer number division
Real number division
Modulus
A4L3 Relational Operators
=
C>
C
>
>=
IN
Equality
InequaLity
Less than
Greater than
Less than or equal (or, set inclusion)
Greater than or equal (or, set inclusion)
Set membership
A4L4 Logical Operators
NOT
OR
AND
Negation
Disjunction
Conjunction
A4L5 Set Operators
+
*
Union
Set difference
Intersection
Page A7
QUICK REfERENCE TO ALPHA PASCAL
.
Page
A—8
A.4.2
Constants
Constants may consist of:
Characters and strings of characters
(in quotes).
TRUE and FALSE
MAXINT (which evaLuates to the largest
Integer on the AMOS system, 12767).
Values of user—defined types
Integers
Decimal and exponential numbers
— least
If
a number contains a decimal point, at one digit must appear to the left of the decimal point.
The exponent in an exponential number is identified by the
"34E—5" represents "0.000034".
"E" symbol..
For example:
A.4.3
Variables
A variable is a simple identifier,
an indexed variable of the form: array—variable
£indexl—expression,...indexN—expresjon] a referenced variable or file buffer variable of the form: pointer—van abte or: fi le—vaniable or a field designator of the form: record—variable
.
field—identifier
A.4.4
Function Calls
Function calls have the form: function—identifier or: function—identifier (parameter
, parameterN)
.
QUICK REFERENCE TO ALPHA PASCAL
Page A9
A,4,5
IF"THENELSE and CASEOF Constructs in Expressions
AiphaPascal allows you to use the IFTHEN—EL5E and CASEOF constructs to conditionally evaluate one of two (in the case of the
IFTHENELSE) or several (in the case of the CASEOF) expressions:
IF Boolean expression THEN expression ELSE expression and:
CASE value OF valuel
: expression; value?
: expression; valueN
: expression;
ELSE expression;
A,5
STATEMENTS
Statements are either simple statements or structured statements,
A simple statement consists of only one statement,
Structured statements are comprised of more than one statement,
You may label statements by writing: label: statement where "label" is an unsigned integer,
A,5,1
Simple Statements
The Pascal simple statements are:
A,5,'Ll
Assignment Statement " assigns a value to a variable: variable expression
A,5,1,2
Procedure Call and take the form: procedure"name or:
Procedure calls invoke the specified procedure, procedure (parameterl, parameter2,
,,,, parameterN)
QUICK REFERENCE TO ALPHA PASCAL
Page A"lO
A,5,1,3
GOTO Statement
The 6010 statement transfers program the labeled portion of the program,
It takes the form:
G010 label control to
A,5,1,4
Null
Statement —
Another permissible simpLe statement is the null statement7TECTs, no statement at alL),
A,5,2
Structured Statements
The PascaL structured statements are:
A,5,2,1
Compound Statements
The compound statement is bracketed with the keywords BEGIN and END, and takes the form:
BEGIN statementi; statement2; ,,,; statementN END,
A compound statement may take the pLace of any singLe statement in the exampLes given in this appendix,
A,5,2,2
Conditional Statements
A conditi aFfjtej€ntcontifs statements whose execution depends on the
result of
a conditionaL test,
These statements may take the form:
11! Boolean expression THEN statement; or:
IF Boolean expression THEN statement ELSE statement; or:
CASE expression OF casel"labeL: statement!: case2—labeL: statement?;
END, caseN—laheL: statementN
(Several case—labeLs, separated by commas, may be written in place of a single case—label,)
QUICK REFERENCE TO ALPHA PASCAL
A523 Repetitive Statements
WHILE Boolean expression DO statement or:
REPEAT statementList UNTIL BooLean expression or:
FOR variabte-identifier := expression TO expression
DO statement
— or:
FOR variabLe—identifier
: expression DOWNTO expression
DO statement
Page A—Il
A524 WITH Statement
The WITH—DO statement aLLows you to access record fields as were simpLe variables:
if they
WITH record—variablel, record—variabLe2,
DO statement record—variabLeN
(Changed 30 ApriL 1981)
•
•
QUICK REFERENCE TO ALPHA PASCAL
Page A—fl
A.6
ALPHA PASCAL STANDARD FUNCTIONS AND PROCEDURES
BeLow is an alphabetic List procedures, that you may use.
of aLL
AiphaPascat standard functions and
To find out what Pages of this book discuss a particular procedure or function, refer to the Index.
ABS
ARCSINH
CHR
COS
DELETE
ERROR
EXP
FILLCHAR
GETFILE
JOBDEV
LENGTH
LOG
MEMAVAIL
ODD
OPENR
P05
PVIRT
ROUND
SHIFT
SPOOL
STR
TANH
UCS
XEQERR
ARCCOS
ARCTAN
CLOSE
COSH
EOF
ERRORINFO
EXPONENT
FILESIZE
GETLOCKS
JOBUSER
LINEMODE
LOOKUP
MOVELEFT
OPEN
ORD
POWER
PWROFTEN
READ
RESET
SCAN
SIN
SQR
STRIP
TIME
VAL
XLOCK
ARCCOSH
ARCTANI(
CONCAT
CREATE
EOLN
ERRORTRAP
EXTENSION
FSPEC
INCHARMODE
KILCMD
LN
MAINPROG
MOVERIGHT
OPENI
PAGE
PRED
PWROFTWO
PEADLN
REWRITE
SEEK
SINH
SQRT
SUCC
TOD
WRITE
XMOUNT
ARCSIN
CHARMODE
COPY
CRT
ERASE
EXIT
FACTORIAL
GET
INSERT
LCS
LOCATION
MARK
NEW
OPENO
PFILE
PUT
RADSO
RELEASE
RND
SETFILE
SIZEOF
STDERRORTRAP
TAN
TRUNC
WRITELN
For a list of aLl standard identifiers and reserved words, see Section
5.4.
"Legal Identifiers."
.
(Changed 30 April 1981)
QUICK REFERENCE TO ALPHA PASCAL
A523 Repetitive Statements
WHILE Boolean expression DO statement or:
REPEAT statementlist UNTIL BooLean expression or:
FOR variabLeidentitier := expression TO expression
DO statement or:
FOR \tariableidentitier := expression DOWNTO expression
DO statement
Page A11
AS24 WITH Statement
The WITHDO statement alLows you to access record fields as it they were simple variables:
WITH recorthvariabie'l, recordvariable2,
DO statement recordvariableN
QUICK REFERENCE TO ALPHA PASCAL
Page A—12
A..6
ALPHA PASCAL STANDARD FUNCTIONS AND PROCEDURES
Below is an.
alphabetic list of
all
AlphaPascat standard functions and procedure that you may use.
To find out what pages of this book discuss a particular procedure or function, refer to the Index.
ABS
ARCSINH
CHR
COS
DELETE
ERROR
EXP
FILLCHAR
GETFILE
JOBDEV
LENGTH
LOG
MENAVAIL
ODD
OPENR
P05
PVIRT
READ
RESET
SEEK
SINH
SQRT
TAN
TRUNC
XEQERR
ARCCOS
ARCTAN
CLOSE
COSH
EOF
ERRORINFO
EXPONENT
FILESIZE
GETLOCKS
JOBIJSER
LINEMODE
LOOKUP
MOVELEFT
OPEN
ORD
POWER
PWROFTEN
READLN
REWRITE
SETFILE
SIZEOF
STDERRORTRAP
TANH
UCS
XLOCK
ARCCOSH"
ARCTANH
CONCAT
CREATE
EOLN
ERRORTRAP
EXTENSION
FSPEC
INCHARMODE
KILCMD
LN
MAINPROG
MOVERIGHT
OPENI
PAGE
PRED
PWROFTWO
RELEASE
ROUND
SHIFT
SPOOL
STRIP
TIME
WRITE
XMOUNT
ARCSIN
CHARMODE
COPY
CRT
ERASE
EXIT
FACTORIAL
GET
INSERT
LCS
LOCATION
MARK
NEW
OPENO
PEILE
PUT
RAD5O
RENAME
SCAN
SIN
SQR
SUCC
TOD
WRITELN
For a list of all standard identifiers and reserved words, see Section 5.4,
'Legat Identifiers.
.
APPENDIX B
THE ASCII
CHARACTER SET
The next few pages contain charts that List the compLete ASCII character set.
We provide the octal, decimal and hexadecimal representations of the
ASCII values.
Note that the first 32 characters are non—printing
Control—characters.
THE ASCII CHARACTER SET
THE CONTROL CHARACTERS
Page 8—2
.
a.
I
I
I
I
CHARACTER
CAN
EM
$5
ESC
FS
65
NULL
SOH
STX
LIX
ECT
ENQ
————— I
I
I
I
I
ACK
BEL
8$
HT
LF
I
I
I
I
I
VT
I
FE
I
CR
I
SO
SI
DLE
DC1
I
I
I
I
DC2
DC3
DC4
NAK
I
I
SYN
ETB
I
I
I
I
I
I
I
I
RS
US
I
I
I
OCTAL
000
001
002
003
004
005
006
007
010
011
012
013
014
015
016
017
020
021
022
023
024
025
026
027
030
031
032
033
034
035
036
037
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
3
I
I
I
I
I
DECIMAL
0
21
22
23
24
25
26
27
28
29
15
16
17
18
19
20
11
12
13
14
30
31
1
2
3
4
5
6
9
10
7
8
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
HEX
I
I
OF
10
11
12
13
14
15
16
17
18
19
1
is ic
1D
1E iF
OB
OC
OD
OE
00
01
02
03
04
05
06
07
08'
09
OA
I
I
I
MEANING
Null. (till character)
Start of Heading
Start of Text
Endotlext
End of Transmission
Enquiry
Acknowledge
Bell code
Back Space
Horizontal Tab
Line Feed
Vertical Tab
Form Feed
Carriage Return
Shift Out
Shift In
Data Link Escape
Device Control I
Device ControL 2
Device ControL 3
Device ControL 4
Negative AcknowLedge
Synchronous Idle
End of Transmission Blocks
Cancel
End of Medium
Special Sequence
Escape
File Separator
Group Separator
Record Separator
Unit Separator
I
I
I
.
S
THE ASCII CHARACTER SET
Page 8—3
PRINTING CHARACTERS
F
I
I
I
I
I
I
I
I
I
I
I
I
4
$
—
1
5
6
7
2
3
4
8
9
I
0
&
(
*
)
+
CHARACTER
C
=
> a
I
OCTAL
DECIMAL
I
I
I
I
"040
I
32
1,041
33
I
I
I
042
I
34
10431
35
044 36
I
045
046
I
37
047
050
I
I
38
39
40
I
I
I
I
051
052
053
I
I
41
42
43
054
055
056
I
I
44
45
46
I
I
I
037
I
47
I
I
060
I
48 tO6lj
49
062
0631
I
064
I
50
51''
52
I
I
I
I
I
I
I
I
I
065
1066
I
I
53
54
067
I
55
0101
56
0711
57
012 58
I
073
074
I
I
59
60
075
076
077
100
I
I
I
61
I
62
63
64
I
I
I
I
I
I
I
I
I
I
I'
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
I
HEXi'
I
20
21
22
23
24
25
I
I
26
27
28
29
I
2A
I,
2B
[
ZC
20
33
34
35
36
37
38
39
2E
2F
30
31
32
3A
38
3C
3D
I
I
I
I
J
I
['
I
I
I
I
I
I
I
SE
3F
40
I
I
I
MEANING
Space
ExcLamation Mark
Quotation Mark
Number
Sign
DolLar Sign
Percent
Sign
Ampersand
Apostrophe
Opening Parenthesis
CLosing
Parenthesis
Asterisk
Plus
Comma
Hyphen or Minus
Period
Stash
Zerq
One'
Two
Three
Four
Five
Six,
Seven
Eight
Nine
Colon
Semicolon
Less
Than
Sign
Than
Question
Mark
Commercial
At
F
F
F
F
THE ASCII CHARACTER SET
I
I
I
I
I
I
I
I
I
I
I s t u
V w x y z
C p q r
I
DEL
"4
I
I
—I
OCTAL
DECIMAL
I
HEX
I
I
I
I
I
I
I
171
172
173
I
I
174
175
I
176
I
1177
160
161
162
"163
164
165
166
167
170
I
I
I
I
I
I
I
I
I
I
I
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
I
I
I
J
I
I
I
I
I
70
71
72
73
74
75
76
77
78
79
7A lB
7C
7D
7E
7F
I
,
I
I
I
I
I
I
I
I
Page
6—5
MEANING
Lower
Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Lower Case Letter
Opening Brace
Vertical Line
Ctosing Brace
Tilde
Delete
I
I
I
I
I
I
I
I
I
I
I
I
I
I
APPENDIX C
ALPHA PASCAL COMPILER ERROR MESSAGES
Below on is an alphabetic List of alt error messages output by the ALphaPASCAL compiler.
For a distussion of how to compile programs, and for information error reporting and error recovery, see
Chapter
4, "Operating
Instructions and Characteristics."
We believe that the error messages below are very exactly what part of your ptbgflffl caused the error.
tell you
where helpful in to look in this manual for more information on the operator, data structure,, or declaration ttwolvid in the error.
explaining
Therefore we have not provided detailed explanations for each error message.
For some of the messages below we: have error and that added notes that givemore tniormation about the
When CMPILR displays an error message, it also disolays the program you try to compile the following small program: line of the that contaths the error arid Doints to the robtem.
For example, if
PROGRAM TestError;
VAR
Numberl
REAL;
Number2
:
STRING;
BEGIN { Try to use addition operator on real and string data. )
IF Numberl + NumberZ = 0 THEN WRITELN('Zero.')
END.
you see the following display:
(Changed 30 April 1981)
ALPHA PASCAL COMPILER ERROR MESSAGES
Page C—?
AlphaPascal Compiler Version 2.0
<
0>
PROGRAM
< 5>—
BEGIN C Try to use addition operator on real and string data. 3
IF Numberl +
Number?
=
0
THEN WRITELNC'Zero.')
?Line 6: CBOPNBN3 In 'x+y5 x and y an not both numeric
?HIT RETURN to continue
< 6>—
7 lines
4.10 seconds,
102.44 tInes/minute
?Total. of 1 compilatIon errors.
The error above occurred because we tried to perform an arithmetic operation on numeric and string data; both Numbenl and
Number!
must be numeric
In order to use the addition operator.
The first eight characters of the error message identify the portion of the compiler that caught the error.
You will probably not need to make note of this identifier.
In many of the error messages, CMPILR actually substitutes into the error message the operator or identifier that is the source of the error.
For example., in the list below, the error message above appears as:
EBOPtIBNJ
In 'x
<op> y', x and y are not both numeric
In our example above, CMPILR substituted into the error message the operator
('<op>") causing the problem, and displayed the mesiage:
IBOPNBN3 In 'x+y', x and y are not both numeric
The symbols in the error messages that are replaced by elements from your program when the message is displayed are:
<op>
Operator
XXX
User—defined Identifier xxx yyy zzz
Keyword
(Changed
30 April 1981)
S
ALPHA PASCAL COMPILER ERROR MESSAGES
Page C—3
C.1
THE ERROR MESSAGES
C??????) ***
Undefined error ***
You should..never see this error message.
Please report it and the circumstances under which you saw it to Alpha Micro.
CANEANX] In 'x AND y', x must be of type eOOL:EAN
CANENOT) In 'NOT x', * must be of type BOOLEAN
See Chaptei'8 for information on BOOLEAN operators.
CASGAST) In 'x:y', tJle types of x and y are incompatible
CASGEIL) It is illegal to assign files to one another
See Chapter 1 for information on the FILE data type.
CASGMAT) In 'x <op> y', the types of x and y are tncompatible
You tried to use a modifying assignment operator on two pieces of data that were of iacompatible type.
For exampLe, you cannot use
"MJMBER you
1= DATA" if PsJMBER is an INTEGER but DATA is REAL, since cannot return an INTEGER result ifyou divide an INTEGER by a
REAL number.
CASGSWL) String contant has wrong length for pacted array
EBDYULB) Undefined labels occur In this function/prote'dure
CBEXARL)
Only ''
and <) are permitted with ARRAYs
See Chapter 7 for information on ARRAY data types.
CBEXCMT] In
'x <relation> y', x and y are Incompatible
CEXFRt) Comparison df FILEs is undefined
CBEXINS)
In 'x IN y', y must be a SET type
CREXINT)
In
'x IN y', x must be compatible with base type of y
CBEXPRL3 only
'=' and '<>'
CBEXRRL) are permitted with pointers only
'' and <>.
are permitted wtth RECORDS
CBEXSRL)
'<' and
'>' are undefined' on Sfls
CBLKDOT]
'.'
(denoting end of source) expected:— assumed missing
CMPILR reached the end at the to
tile, but saw
no period.
Remember end all program and module ftits with a period.
(BOPINT) Only INTEGER operands are permitted wtth Cop>
CBOPIOS]
Only INTEGER or set operands are 'permitted with Cop>
CSOPNBN) In
'x <op> y', x and y are not both numeric
CBOPNBSJ
CBOPNOS)
In 'x <op> y', x and y at'e not both sets.
Only numeric or set operands are permitted with<op>
CBOPNUM) Only numeric (INTEGER or REAO operands are permitted with <op>
ECALAPS)
Preceding argument must not be a packed char field
CCALARL] The preceding string constant has wrong length
CCALARSJ The preceding SET variable has wrong size
ECALART) The preceding argument has wrong type
ECALARVJ The preceding argument must be a variable expression
CCALCHR] The preceding must be of type CHAR
(Changed 30 April 1981)
ALPHA PASCAL COMPILER ERROR MESSAGES
Page
C—4
CCALEXT] EXIT(x) where x is a standard func or proc is illegal
You may only supply EXIT with the PROGRAM keyword or the name of your own Drocedure or function that you want to exit; you 'nay not suppty the name of a function or procedure in the library.
ECALFIL) Preceding argument must be of FILE type
CCALFRM] Formal procedures and functions not implemented
CCALINT] The preceding argument must be of type INTEGER
CCALIOR] Preceding argument must be of type INTEGER or REAL
CCALLPR) 'C' expected —— assumed missing
CCALNRS) Preceding argument must be a pointer or non—REAL scalar
CCALOPM) INPUT, OUTPIJT,or RANDOM expected ——
INPUT assumed
See Chapter 10 for information on file—identifiers.
CCALPAC) Must be a packed array of char or a char element
CCALPTV) The preceding must be a pointer variable
CCALRDP] It is illegal to read into a packed: char fiej.d
CCALRDT] Arguments to read must be INTEGERflAL, CHAR, or String
CCALSCNI Only '' and '<> are permitted here
ECALSEX] The preceding must be a string expression
CCALSVR] The preceding must be a string variable
CCALTFA] Too few arguments supplied
CCALTGS) The preceding must not be a string or a real.
ECALIGI) The preceding constant Is of incorrect type for variant
See Chapter 7 for information on RECORD variants.
ECALTMA] Too many arguments supplied
CCALTXT) Preceding argument must be of type TEXT (FILE OF CHAR).
CCALWRM] Preceding modifier must be of type INTEGER
CCALWRT] Must be INTEG€R, REAL, CHAR, String, or pck'd arry of chr
CCSDJNK] Junk after <constant definition> — scanning
CCSTSGN] Only INTEGER and REAL cônstants may be signed
CEXPORX) In 'x OR y', x must be of type BOOLEAN
CFACCET] In 'CASE x OF ...', x must be a non—REAL scalar type
CFACCLT] In 'CASE x OF ...'., labels must be compatible with x
CFACCVT) In CASE expressions, all cases must have compatible types
CFACDCS] The previous case label has already. appeared
CEACIFT] THEN and ELSE expressions must have compatible types
CFACRTL] Proc or func too large, split it into smal.ler pieces
EFACSCK] In set constructor C——], set elements must be scalars
CEACSCT) In set constructor C——), all elements must be compatible
CGVDFIL] Global files must be declared in PROGRAM file
EGVDFWP] x present and x never declared for some x
CGVDJNK] Junk after <variable definition> —— scanning
CINIESF) Empty source file
CINILTL] First source line too long —— truncated to 132 characters
CINIPOM) PROGRAM or MODULE expected ——
'PROGRAM;.!
assumed
CINIRPR] 'P expected —— inserting
')'
CINISEM)
';'
CINISOI)
':
CINISOP)
5' expected
—— inserting
';' or
<identifier> expected —— or
'C' expected ——
Inserting inserting
';'
';'
(Changed
30 April 1981)
ALPHA PA$CAL COMPILER ERROR MESSAGES
Page C—S
CLADERR3 *** Compiler error in LOADADDRES$ ***
You should never see this error message.
Please report it and the circumstances under which you saw it to Alpha Micro.
CLADPCK) Packed variables may not be used in this context
CLBLDDC) Label already declared tn this scope
CMPATBG] Maximum string slze,$s 255
CPRDAFL) Only formal (VAR) FILE parameters are,:permtt'ted
ERR DDDF] Function or procedure already declared ,f9rward
CPRDDDP) Parameter—list must only appear in FORWARD declaration
CPRDFNR] ':
<result type identifier>'
expected —— assumed missing
CPRDFTM] Function type not compatible with forward declaration
For information on forward decliarat tons, see Chapter 6.
EPRDLPX]
(' expected
—— assumed missing
CPRDNST) Procedure/function declarations nested too deeply
EPRDPDF] Function or procedure previously def toed
CPRDPRF] Previously declared a function in same scope
CPRDPRP] Previously declared a procedure tn,same scope
EPRDSSR) Function must be of scatar, subrange, or pointer type
ESCNINSJ Giving up scan —— inserting xxx
CSCNMIS] Giving up scan —— xxx assumed missing
(SELATO) In xty) or xC——,y), x or xE——) must be of ARRAY type
CSELERR]
*** Compiler error In SELECT ***
You should never see this error message.
PLease report it and the circumstances under which you saw it to Alpha Micro.
ESELFOP] In 'x', x must be of pointer or FIi.E type
ESELIXT] In xCy), y must be compatible with index type of x
[SELNIS) Only enclosing func identifiers may be, used as variables
CSELNSF] In 'x.y', y must be a 'field of the RECORD x
ESELRTO] In 'x.y', x must be of RECORD type
ESELSIF] Standard function identifiers may not be used as variabLes
For a list of'the standard identifiers, see Chapter 5.
CSELSXO] In xCy], y must be of non—REAL scatar type.
CSIDUDF] 'XXX' is undefined
CSIDWRC) 'XXX' Is not a TYPE/CONST/VAR/FIEt.D/PROCEDURE/FUNCTION identifier
CSMPNUM) In '—x', x must be numeric
CSTMBID] Wrong BEGIN—END identifier —— XX4C expected.
For information on
BEGIN—END
Labels, see
Declarations."
Section 6.2, "Label
CSTMCSD] The oreceding case label appears more than once
ESTMCST]
The preceding case label has wrong type
[SIMOOW] DO without WHILE, FOR, or
WITH
CSTMEWI]
ELSE without IF or CASE
CSTMFFK] Final FOR value must, be of scaler type
CSTfIFFT]
FOR variable and final value have incompatible types
(Changed 30 April 1981)
ALPHA
PASCAL COMPILER ERROR MESSAGES
Page C—6
CSTMFIKJ Initial FOR value must be- of scalar type
[SIMFIT] FOR variable and Initial value have incompatible types
CSTMFVF] In 'FOR x:=...', x must not be a formal variable
CSTMFVK) Irt 'FOR x:...', x must be a non—REAL scatar variable
ESTMGTOJ GO.TO statements are not permitted without (*fl+*) option
CSTMMDLJ Definition for this label has already appeared
CSTMPEX) Function calls are not legal as statements
CSTMPEX) Procedure identifier was expected
CSTMRTL] Proc or func too large, split It into smatter pieces
CSTMTI4I] THEN without IF
CSTMIJLB) Undeclared label
CSTMIJWR) UNTIL <expression> without REPEAT
CSTMWRT) In 'WITH *
DO
...', x must be a RECORD variable
See Chapter 9 for information on accessing record fields with
WITH—DO.
CSTMWT$) WITH statement has caused too many nest-ed scopes
ESTRERR) ***
You
Compiler error in STORE *** should never see this error message.
Please report it and the circiznstances under which you saw tt to Alpha Micro.
CTOKEDG] Digit (0—9) expected in exponent
—— assumed missing
CTOKEOF) Unexpected end—of—source—file encountered
Remember to end every program or moduLe file with a period.
CTOKFDG) Digit (0—9) expected in fraction —— assumed missing
CTOKILC] Illegal character encountered —— ignoring
CTOKINF) Include file not found
See Chapter 4 for information on Include Files.
CTOKIRGJ Integer constants must be in the range +—32767
ETOKLTL) Line too long —— truncated to 13-2 character-s
CTOKNIN) File includes (*$j ———*) may not be nested
CTOKSLS) Unterminated string (multi—line strings not permitted)
CTRMNBN) In 'x/y', both operands must be numeric
CTRYINS] xxx or yyy expected —— inserting xxx
CTRYINS) xxx or yyy expected —— inserting yyy
CTRYINS) xxx, yyy, or zzz expected
—— inserting xxx
CTRYINSI xxx, yyy, or zzz expected —— inserting yyy
CTRYMIS) xxx expected
—— yyy assumed missing
CTRYSCNJ xxx expected —— scanning
CTRYSCN) xxx or yyy expected —— scanning
CTRYSCN] xxx, yyy, or zzz expected —— scanning
ETYDFWP] x present and x never declared for some x
CTYDJNK) Junk after <type definition> —— scanning
CTYPBTF) In 'ARRAY Cx) OF y', y must not be a FiLE type
CTYPCTK) In 'CASE x OF ...', x must be a scalar type identifier
CTYPCTR) In 'CASE x OF ...', x must not be of type REAL
CTYPIXB) Array is too large
(Changed 30 April 1981)
V
ALPHA PASCAL COMPILER ERROR MESSAGES
[TYPIXR]
[TYPIXT]
CTVPLGH]
[TYPNST]
CT VPR F F]
CTYPRGE]
[TV
PS CI]
CT '(P 5 R R ]
CT '(PS TB]
[TV PS TB]
[TYPSTK]
[TVPSTR]
In
In x
Dec
Rec x, y where x and y are incompatible
Set
Set
ARRAY Cx] OF
ARRAY Cx] OF y where x>y is larations too deeply nested ord fields must not he of is too large is too
In SET OF
In SET OF large x x x must not be of type REAL y', x must he a scalar type
illegal
FILE type
A string constant identifier must not appear
Subranges of type real are illegal
(must be <
SET OF O 4095) must be a scalar type must not be of type REAL here
CTYPSXR]
CTYPSXT]
CTVPTTE]
[yR DFWP]
CV DJNK]
STRING[x]
STRING[x]
In 'CASE x x present
Junk after inust h where x
OF and ave
1
CXPRSSP] Function must be of sca
< x
< x never declared for some x
<variable definition>
255 is not an integer tag type is incompatible scanning with x
CXPRAFL] Only formal
CXPRLPX]
'(' expected
(VAR) FILE parameters are nermitted assumed missing lar, subranqe, or pointer type
Page C—?
(Changed 30 April 1981)
S
ALPHA PASCAL USER'S MANUAL
Index
$6 compiler options
SI compiler option
SL compiler options
$P compiler option
SQ compiler options
SR compiler options
S
•
S
•
S
•
•
5
*
S
•
S S
S
S
4—7
4—7
4—8
4-10
4—10
4—10
.INC files
.PCF files
.PO? files
.PSB tiles
.
.
.
.
/LINI( linker option
/SMASH linker option
•
S
S
S
4—2
4—11
4—5, 4—11
4—13, 15—1
4—15, 15—2, 15—5
4—16, 4—19
Aborting command tile execut ion
ABS
Actual parameters
5
*
AIphaBASIC file locks
AMOS file specification
.
AMOSfiles
AND
•
S
•
S
ARCCOS
ARCCOSH
ARCSIN
ARCSINH
ARCTAN
ARCTANH
Arithmetic operator
.
ARRAY
Array index
ASCII
•
S
•
•
•
0
•
5
• *
ASCII character set
.
ASCII value
Assembly language subroutines
Assignment operator
Assignment statement
.
S
•
S
*
S
S
S
S
S
S
S
S
11—2
12—3
6—11
14—6
10—16
7—15,
7—3
1
—2
12—3
12—2
12—3
12—2
12-3
8—5
7—8,
7—8
7—4
10—14
15—5
11—1
11.—i
3—4,
3—2,
9—1
4—13, 15—1,
8—3
16—4
BEGIN
Bibliography
Block
Block structure
.
Blocking records
S
•
S
2—3,
1—1
5—1
2—2
10—1 9
5—4
Page Index—I
Compiler
CMPILR
Charmode
CHR
Clearing fiLe tacks
Clock, System
CLOSE
SCAN
CHAR
CASE—OF
BOOLEAN
ALPHA PASCAL USER'S MANUAL
.
10—3
•
7—3,
15—4
Buffer variable
CASE expressions
.
.
.
8—9
Case label
• a
•
7—18
•
*
7—18, 9—6
.
5—11,
7—4, 15—4
•
Character array functions and procedures
FILLCHAR a
13—7
MOVELEFT
• a a
13—7
MOVERIGHT
13—8
13—9
Character editing
.
.
Character mode
.
Character set a
• a a
•
.
10—14
11—6
*
•
7—4
•
10—2, 10—14, 11—6
.
11—1
.
14—5
.
14—11
10—17 a a
* a
•
•
• a
• a
4—5
Collating sequence
•
• a
•
.
7—4
Command files
Comments
• a a
• a
•
4—20, 11—2
2—3, 5—4 a
•
4—5
Compiler display
Compiler listing
.
Compiler options
.
$6+ and $6—
SI
$L+ and $L—
.
*
• a a a a a
*
•
•
4—10
•
4—8
.
4—7
.
4—7
.
4—7
4—8
4—10
4—10
4—10
$Q+ and $0—
• a a
$R+ and $R— a
Compiling a program
Compiling a single file
Compiling/updating one
* module
Compound statement
• a
CONCAT a
CONSI
Constant definition
.
*
Constants a
Control—C handling
COPY
COS
COSH
CREATE
*
•
• a
•
• a
2—7
4—20 to
4—21
4—22 a
•
•
•
5—4
.
13—2
.
6—4
5—11, 6—4
6—4, 8—7
14—15
13—2
12—1
12—2
•
10—18
*
.
2—4
11—7
Creating a source file
CR1 a
•
Data objects
Data stack
Data structures
.
6—1
15—2
2—2
Paqe Index—2
.
4
ALPHA PASCAL USER'S MANUAL
Datatype
Debugging
Decimal notation
Declarations
.
.
Declaring
Functions
Labels
S
.
.
Procedures
.
Type
S
•
Variables
.
.
.
Declaring external ci ements
Declaring variables
.
S
Defining constants
S
S
DELETE
Disk blocks
Displaying file locks
Dynamic variables
.
—
S
S
•
•
S
.
S
S
S
S
*
S
S S
S S
S
S
S
S
•
S
S
S
S
S
*
S
S
6—4, 7—1
14-3
5—10
6—1
6—6
6—2
6—9
6—i.
6—1, 6—6
6—12
7—2
8—7
10—21, 13—3
10—15
14—5
7—19, 11—3
E symbol
END
End—of—file
End—of—tine
End—of—line separators
EOF
EOLN
ERASE
ERROR
Error codes
Error handling
ERRORINFO
EXIT
EXP
EXPONENT
Expression
Expression handling
Expressions
Assignment operator
CASE—OF construct
.
.
IF—THEN—ELSE
EXTENSION construct
EXTERNAL
External declaration
External library
.
Modifying
Version number
.
.
*
Version stamp
S
S
S
S
S S
S
•
S
S
S
S
*
S S
S
S
S
S
S
S
S
S
S S
S
S
S
S
S
S
S
5—10
2—3, 5—2, 5—4
10—3, 10—16
10—4
10—15
10—3, 10—15
10—4
10—1 9
14—16
14—13
14—12, 15—5
14—13
3—5, 9—2, 14—15
12—3
12—4
8—1
3—2
S S
*
S
S
S
S S
•
S S S
S
3—2
3'S, 9—6
3—2,
8—8, 9—5
10—19
3—3,
6—12, 16—1
6—12
2—?,
3—4, 4—1, 6—12, 16—1
1s6—5
4—18, 16—5
4—1 8
FACTORIAL
FALSE
Field
FILE
S S S S
S
S
S S
12—4
7—3
7—16
7—15,
10—16, 15—5
Page Index—3
ALPHA PASCAL USER'S MANUAL
File error codes
File handling .
File to*ks
. .
*
File search pattern
File specification
File window
File—identifier
.
FILESIZE
FILLCHAR
.
Floating point numbers
FOR—DO
Formal parameters
Formatting output
FORWARD
Forward declaration
FSPEC
Function
Function block
.
Function call
.
Function declaration
Function result
•
. .
*
.
*
S a
•
•
S
*
.
S
*
*
*
*
S
* *
S S a a
•
S
* s
*
S
.
• a
* * * *
GET
GETFILE
GETLOCKS
.
GOTO
Heading
Heap
I/O errors
Identifier
Identifier scope
.
IF—THEN
IF—THEN—ELSE
Imagemode
Include file
Include files
Indentation conventions
INFOREC
INPUT
INSERT
INTEGER
Integer numbers
.
.
.
INTERACTIVE
Invoking functions a s
•
S
*
S S
•
S
S
* a S
* a a
•
S S
*
S
•
* a
*
* a
*
*
S
*
*
S
.
S
S
• a
S
*
JOBDEV
JOBUSER
I(8D
KEYBOARD
14—14
3—4
14—5
4—3
10—16
10—3
7—16,
10—16
10—20
13—7
3—4
9—9
6—11
10—10
6—10
6—10
7—16, 10—21
15—3
6—7
8—1
6—6
6—6
10—5
10—22
14—5
4—7, 9—2 to
9—3
5—1
7—22, 11—3, 11—5
14—13
5—2,
5—5
2—2, 5—7
9—4
9—5
11—6
4—7
14—3
5—4
14—13
10—2
13—4
6—4, 7—2, 15—4
5-9, 10—10
7—11
6—7
10—23
10—24
10—2, 10—14
10—2,
11—6
Page Index—4
.
3
.
ALPHA PASCAL USER'S MAMIAL
Keywords
ARRAY....
BEGIN
.
CASE
.
CASE—or
CONST
.
.
END
EXTERNAL
.
FILE
.
.
FOR—DO
FORWARD
FUNCTION
6010
.
IF—THEN
IF—THEN—ELSE
LABEL .
.
.
MODULE
PACKED
PROCEDURE *
PROGRAM
.
.
RECORD
REPEAT—UNTIL
SET
VAR
WHILE—DO
WITH—DO .
KILCMD
.
.
Label declaration
LCS
Legal identifier
LENGTH
Library version check ing
Line printer spooler a
S
Linked list
Linker
Linking a program
Linking a single file
*
.
L N
LOAD
•
•
S
.
a
*
Local procedures
Local, reference
LOCATION
LOG
Logical operators
.
Logical records
.
LOOKUP
Loop
*
• a a a
* a a a a a a a
• a a
• a a a a
.
S S
*
•
S S
• a a a a a
• a a a a a a a a a a
6—2
13—4
5—5,
13—5
4—17
14—3
7—22
4—11
2—7
4—21
12—4
15—6
6—6
5—7
14—1
12—4
8-6
10—16
10—24
9—9
6—1
2—3,
7—8
2—3,
7—18
9—6
6—4
2—3,
3—3,
7—15
9—9
6—10
6—6
4—7,
9—4
9—5
6—2
5—2
7—8
6—9
5—1,
7—16
9—9
7—13
6—6
9—8
9—10
11—2
5—5
5—3
5—3
6-12, 16—1
9—3
6—1
MAINPROG
MARK
Mathematical functions
ABS
ARCCOS
* a
.
a a
.
*
S a
14—2
7—22,
12—1
12—3
12—2
11—3, 11—5
(Changed 30 April 1981)
Page Index—S
ALPHA PASCAL USER'S MANUAL
ARCCO$H
ARCSIN
ARCSINH
ARCTAN
*
ARCTANH
COS
.
.
COSH
EXP
.
EXPONENT
FACTOR IAL
LN
LOG .
ODD
.
POWER
.
PWROFTEN
PWROFTWO
*
•
*
ROUND
SHIFT
.
*
SIN
.
.
SINH
.
*
54W
.
SQRT
.
STR...
TAN .
.
TANH
.
TRUNC
MAXINT
MEMA
VA IL
Modifying assignment
Modifying STDLIB operators
MODULE
MOUNT.INC
Mounting a disk
*
*
MOVELEFT
MOVERIGHT
Multi—dimensional arrays
Multi—user file locks
*
Multiple libraries
*
•
•
*
*
*
* *
•
*
*
*
* a
•
*
*
*
*
•
*
•
* *
.
*
.
• a
• a
1 2—1
12—2
12—6
12—6
12—6
12—1
12—2
12—7
7—2,
14—2
8—7
16—4
5—2
14—10
14—9
13—8
139
7—10
14—5
16—1
8—4
12—3
12—2
12—3
12—2
12—3
12—1
12—2
12—3
1 2—4
12—4
12—4
12—4
12—4
12—4
12—5
12—5
12—5
12—5
12—6
12—6
Napierian logarithm
Natural logarithm
NEW
NIL
Non—local reference
NOT
Null statement
Numbers
Numeric constants
Numeric literals
Numeric notation
*
*
•
* *
•
*
•
*
*
*
*
•
.
*
*
*
*
•
•
* * *
S
*
• *
*
* a
*
12—4
1 2—4
7—20,
7—20
7—22,
5-7,.
7—3
9—3
5—9
6—1,
8—7
6—4
5—9
11—3, 11—5
(Changed 30 April 1981)
Page Index—6
.
.
ALPHA PA$tAL USER'S MANUAL
ODD
OPEN
OR
Opening files
.
OPENO
OPENR .
Operator
Operator precedence
GR D
OUTPUT
12—4
10—16, 10—25 io—io:
10—25
10—26
8—1
3—3, 8—1 to 8—2
7—3
7—2, 7—4, 11—3
10-2
PACK
Packing data
PAGE
Parameters
Pascal
PC.DO
PCL.DO
PCU.DO
PEILE
PL.DO
PLINK
Pointer
Pointer data type
POS
POWER
Pee—declared constants
PRED
Previous versions of Al phaPascal
Printer queue
Procedure
Procedure call
.
Procedure declaration
PROGRAM
Program declaration
Program listing
.
.
Program name
Program structure
•
•
S
.
S
.
•.
0
*
5
Prohibiting GOTOs
PU.D0
PUT
PWROFTEN
PWROFTWO
7—8
7—8
10—13
15—3
2—1
4—20
4—21, 11—2
4—22
10—26
4—21
4—11, 15—1
7—19 t 7—20,
7—19
13—3,13—5
12—4
8—7
7—2, 7—4, 11—4
3—1
15—4
14—3
15—3
9—1
6—8
5—1, 6—1
2—3, 6—1
4—8
6—1
5—1
4—7
4—21
10—5 to 10—6
12—5
12—5
Quiet compiler display
RADSO
Random tiles
• RANDOMIZE
Range checking
READ
READLN
REAL
Real nunbers
4—10
10—26
10-1 5
12—5
4—10
10—7
10—8
7—3, 15—4
5—9, 10—10
(Changed 30 Apr11 1981)
Page Index—?
ALPHA PASCAL USER'S MANUAL
•
RECORD
Record variants
Recursion
Reference parameter
Registers
RelationaL operator
RELEASE
RENAME
REPEAT—UNTIL
.
.
Reserved words
.
*
RESET
REWRITE
RND
ROUND
Running a program
.—
7-16, 15—5
7—18
3r5
6—12, 15—3
15—2
8—6
7,22, 11—5
10—27
9—9
1—4, 5—5 to 5—6
10—13
10—13
12—5
12—6
2—8
Sample program
Array
Demonstration
EOF
ERRORTRAP
Formatting output
Forward declaration
Function
GET and PUT
GETFILE and SETFILE
GOTO5
Identifier Scope
IF—THEN in expressions
Linked list
Modifying assignment operator
MathematicaL functions
Pointers
.
Random fiLe
.
REPEAT—UNTIL
Sets
WHILE—DO
.
.
.
Scalar constant
.
Scalar data type
SCAN
Scientific notation
Scope of identifier
$
SEEK
Semicolon
Sequential FiLes
SET
Set operators
SETFILE
Setting file locks
SHIFT
Simple data type
SIN
SINH
SIZEOF
S
S
S
S
*
S
S
S
S
S
S
S
S
S
7—9
2—3
10—4
14—12
10—11
6—10
6—8
10—6
10—23
9—2
5—9
8—9
7—21
8—5.
12—7
7-20
10—29
9—9
7—14
9—8
7—5
7—1, 7—5
13—10
5—10
2—2,
5—7
10—27
5—2
10—15
7—1?., 15—4
7—13, 8—7
10—27
14—5
12—6
7—1
12—1
12—2
14—1
(Changed 30 April 1981)
Page Index—8
.
.
.
U
ALPHA PASGAL USER'S MANUAL
Spec ing convent ions.
SPOOL
Spool.
switches
SPO0L.jNC
SQR
.
SQRT
Stack
Standard constants
Standard data type
Standard Identifiers
Standard Pascal
Statement label
Statement separator
Static variables
.
STDERRORTRAP
.
STDLIB
SIR
STRING
String constant
String constants
STRING data type
String functions and
CONCAT cOPY
DELETE
INSERT procedures
L CS
LENGTH
Pos
STRIP
UCS
VAL.
String titeral
String notation
Stnngs
.
.
STRIP
Structured data type
Subrange data type
Subscript
Subset operator
S
UCC
Superset operator
System queue
.
S
S
S
S
S
S
S
S
S
S
S
S
S
S
S
S
5—2
14—3
14—3
14—3
12—6
12—6
11—3,
15—2
8—7
7—1
1—4, 2'3,
5'—S to 5—6
2—2
6—2
5—2, 5—4
7—19
14—13
16-1
12—6
3—6, 75, 7—10, 15—4
5—li
6—1, 8—7
5—11
13—2
13—2
13—3
13—4
13—4
13—5
13—3,
13—5
13—6
13—6
13—6.
5—il, 6—4,
5—10
5—10
13—6
7—1, 7—6
7—6
7—8
8—6
7—2,
8—6
14—6
7—4, 11—5
TAN
TANH
Terminal dispLay
.
Terminal screen—handling
TEXT
TIME
I®
TRUE
12—1
•
12—2
. .
.
.
4—9
.
11—7
7—11
14—11
.... 14—11
7—3
(Changed
30 April. 1981)
Page Indn9
I
ALPHA PASCAL USERS MAI'MJAL
liv..
Type decLaration
.
* * *
* *
*
.
.
12—7
10—2, 10—14
6—4
Unmountinq a disk
.
*
.
Updating a singLe module
User—defined data type
User—defined ERRORIRAP
User—defined functions
User—defined subrange
VAt
Value parameter
.
.
*
Value parameters
VAR
VariabLe decLaration
VariabLes
Variant
Version ntnber
Version stamp
.
-
VUE
.
*
*
*
S
*
S
*
S
•
• * *
•
*
* *
.
•
.
.
•
.
13—6
14—9
4—21
7—5
14—12
6—6
7—6
13—6a
15—3
6—12
6—6
2—2, 6—6, 7—2
7—1, 8—8
7—18
4-18
4—18
2—5
WHILE—DO
WITH—DO
* *
WRITE
•
.
*
WRITELN
Writing an external
I
• * * ibrary
* *
S
XERROTRAP
XLOCK
XLOCK.SY$
XNOUNT
S
* *
*
*
*
•
* •
9—8
9—10
10—9
10—9
16—4
14—16
14—5
14—6
14—9
Page Index-lO
(Changed 30 April 1981)
ડાઉનલોડ કરો
જાહેરાત