Digital PDFs
Documents
Guest
Register
Log In
AA-L315A-TM
May 1983
256 pages
Original
8.5MB
view
download
Document:
PASCAL Language Manual Ver 1 Sep83
Order Number:
AA-L315A-TM
Revision:
0
Pages:
256
Original Filename:
AA-L315A-TM_PASCAL_Language_Manual_Ver_1_Sep83.pdf
OCR Text
TOPS-20 PASCAL Language Manual AA-L~31 5A-TM September 1983 This document descnibes the elements of the PASCAL language supported by TOPS-20 PASCAL. OPERATING SYSTEM: SOFTWARE: TOPS-20 VS.1 (2040,2060) TOPS-20 V4.1 (2020) PASCAL V1.0 LINK VS.1 RMS V1.2 Software and manuals should be ordered by title and order number. In the United States. send orders to the nearest distribution center. Outside the United States, orders should be directed to the nearest DIGITAL Field Sales Office or representative. Northeast/MId-Atlantic Region Central Region Western Region Digital Equipment Corporation PO Box CS2008 Nashua, New Hampshire 03061 Telephone:(603)884-6660 Digital Equipment Corporation Digital Equipment Corporation Acc€tssories and Supplies Center Accessories and Supplies Center 1050 East Remington Road 632 Caribbean Drive Schaumburg, Illinois 60195 Sunnyvale, California 94086 Telephone:(312)640--5612 Telephone:(408)734-4915 digital equipment corporation. marlboro massachusetts First Printing, September 1983 ~: Digital Equipment Corporation 1983. All Rights Reserved. The information in this document is subject to change without notice and should not be construed as a commitment by Digital Equipment Corporation. Digital Equipment Corporation assumes no responsibility for any errors that may appear in this document. The software described in this document is furnished under a license and may only be used or copied in accorcfance with the terms of such license. No responsibility is assumed for the use or reliability of software on equipment that is not supplied by DIGITAL or its affiliated companies. The following are trademarks Of Digital Equipment Corporation: ~D~DD~D'M DEC DECmate DECsystem-10 DECSYSTEM-20 DECUS DECwriter DIBOL MASSBUS PDP piOS Professional Rainbow RSTS RSX UNIBUS VAX VMS VT Work Processor The postage-prepaid READER'S COMMENTS form on the last page of this document requests the user's critical evaluation to assist us in preparing future documentation. ----------~-------------------------------- ------------.------- CONTENTS PREFACE CHAPTER 1 INTRODUCTION OVERVIEW OF PASCAL · Data Types . . • . • • • • . • • • • • • . Structure of a PASCAL Program . • . . 1•1•3 Definitions and Declarations . . . • . · . . . 1 • 1 .4 Executable Statements 1.1.5 Subprograms •...•••• • 1.1.6 Compilation Units .... · 1.2 LEXICAL ELEMENTS • . • . • • . · 1.2.1 Character Set • . . . . • . . • . • • . • • • 1.2.2 Reserved Words • • ••. 1.2.3 Identifiers .•••.••• 1.2.3.1 Predeclared Identifiers · 1.2.3.2 User Identifiers • • • • • • • • 1.2.4 Special Symbols • • 1 .3 DELIMITERS . • . • • • • • • • • • . 1 .4 DOCUMENTING YOUR PROGRAM • · 1.5 THE %INCLUDE DIRECTIVE • . • . . • • • . · • . . 1•1 . 1-2 1.1.1 1 • 1 .2 • 1- 2 CHAPTER 2 2.1 2.2 2.2.1 2.2.1.1 2.2.1.2 2.2.1.3 2.2.1.4 2.2.2 2.2.2.1 2.2.2.2 2.2.2.3 2.3 2.3.1 2.3,.1.1 2.3.1.2 2.3.1.3 2.3.1.4 2.3.1.5 2.3.2 2.3.2.1 2.3.2.2 2.3.2.3 2.3.2.4 2.3.3 2.3.4 2.3.4.1 2.3.4.2 2.4 2.5 2.6 • 1-2 . 1-4 • 1-4 • 1-4 . 1-5 . 1-5 • 1- 5 · 1-0 · 1-7 . 1-7 • 1-8 • l-8 • 1-8 • 1-9 1-10 PASCAL DATA TYPES DECLARING DATA TYPES · • • • • • SCALAR TYPES • • • • Predefined Data Types . • • • . INTEGER Data Type • • • • • • REAL Data Type • • • • • • • • BOOLEAN Data Type • • •• CHAR Data Type • • • • • • • User-Defined Scalar Data Types • Enumerated Data ~rypes • • Subrange Data Types • • • The ORD Function • · STRUCTURED DATA TYPES Array Types • • • • Multidimensional Arrays String Variables • • • • • • • • Initializing and Assigning Values to Array Type Compatibility. • Array Examples • • • • • • · Record Types . • • • • • • • Records with Variants Assigning Values to Records • • • . Record Type Compatibil~ty Record Examples Set Types • • • • • • • • File Types • • • • • • • • • Internal and External Files Text Files • • • • • • • • • • POINTER TYPES . • • • • • • • • • PACKED STRUCTURED TYPES • • • • • TYPE COMPATIBILITY • • • • • • • • • • • iii • • • . · . • • . • 2-1 . 2-2 . 2- 2 • • • 2-2 • • • 2- 3 • • • • • 2- 4 • • • • • 2-4 • • 2-5 • • • • • 2- 5 • • • • • 2-6 • • • • • 2-7 · • 2-8 • • • • • 2- 8 • • • • • 2-9 • • •• 2-11 Arrays 2-12 • 2-14 • • •• · • •• • • • 2-15 2-15 2-17 2-19 2-19 2-21 2-22 2-24 2-25 2-25 2-26 2-28 2-29 • • •• • • •• • • • • CHAPTER 3 3. 1 1. 1 . 1 3. 1 .2 1. 1 . 3 3.1.4 3 . 1 .5 3.2 CHAPTER 4 4•1 4 .2 4•3 4 .4 4.5 4.6 CHAPTER 5 5.1 5.2 5.3 5.3. 1 5.3.2 5.3. 3 5.4 5 .4. 1 5.4.2 5.4 . 3 5.5 5.6 5.7 CHAPTER 6 11.1 6. 1. 1 6.1.1.1 6.1.1.2 6.1.1.3 11.1.1.4 6.1.2 6.2 6.3 6.3.1 6.3.1.1 6.3.1.2 6.3.1.3 6.3.2 6.4 6.5 6.6 11.7 6.S CHAPTER 7 7.1 EXPRESSIONS OPERATORS Arithmetic Expressions. Relational Expressions . Logical Expressions ... . Set Expressions ... . Precedence of Operators SCOPE OF IDENTIFIERS . • . . · . . · . . . · · . . · . 1-1 3-1 3-4 3-5 3-5 . 1-6 · 3-7 . . . . • • • • • 4- 3 · . · . . · . . . . · . . . . 4-4 4-5 4-6 4-7 . . . . · · . · • • • • . . . · . . . . . . . • . . · · . . · . .. 5-2 5-2 5-4 5-4 5- 5 5-6 5-8 5-S 5-10 5-11 5 -12 5-13 5-14 6-1 6-'-1 11- 5 6-6 PROGRAM HEADING AND DECLARATION SECTION THE PROGRAM HEADING LABEL DECLARATIONS . . CONSTANT DEFINITIONS . TYPE DEFINITIONS . . . VARIABLE DECLARATIONS VALUE DECLARATIONS . . · 4-2 PASCAL STATEMENTS THE COMPOUND STATEMENT . THE ASSIGNMENT STATE~ENT • CONDITIONAL STATEMENTS . . . The IF-THEN Statement The IF-THEN-ELSE Statement The CASE Statement . . REPETITIVE STATEMENTS . . . The FOR Statement . . .. The REPEAT Statement . The WHILE Statement THE WITH STATEMENT . THE GOTO STATEMENT . THE PROCEDURE CALL . · . . . . · ..... . . . . . . . ... . . . . . . PROCEDURES AND FUNCTIONS PREDECLARED SUBPROGRAMS . • . . .. . • Predeclared Procedures · • .. • • Input/Output Procedures Dynamic Allocation Procedures The MARK and RELEASE Procedures • Miscellaneous Predeclared Procedures. Predeclared Functions FORMAT OF A SUBPROGRAM PARAMETERS . . ' . . . Formal Parameters Value Parameters. .. . • Variable Parameters • • Formal Procedure and Function Parameters Conformant Arrays . . . . . .. . • DECLARING A PROCEDURE · • DECLARING A FUNCTION . FORWARD DECLARATIONS . • . . • . EXTERNAL SUBPROGRAMS . MODULES FOR SEPARATE COMPILATION • • • • · . . • • • . • • • • • 6-9 . . . . . . • . 6-10 6-12 6-20 6-21 11-21 6-22 6-23 6-24 6 - 25 6-28 6-32 6-35 6-36 6-37 INPUT AND OUTPUT FILE CHARACTERISTICS • . . . . . . . . . . • . • . 7-2 iv 7•1. 1 7. 1. 2 7•1. 3 7.1.4 7.2 7.2.1 7.2.2 7.3 7.4 7.5 7.6 7.7 7 .7.1 7.7.2 7.7.3 7 • 7 .4 7.7.5 7 •7 •6 7.8 7.9 7.10 7.11 7. 12 7.13 7.14 7.15 7.10 CHAPTER 8 8.1 8.2 8.3 8.4 8.4.1 8.4.2 8.4.3 8.4.4 8.4.5 8.4.6 8.4.6.1 8.4./s.2 8.4.6.3 8.5 8.5.1 8.ry 8.7 CHAPTER 9 9.1 9.2 9.3 9.4 9.4.1 9.4.2 9.4.3 9.4.4 9.4.5 9.4.6 9.4.7 Fi Ie Names . . . . . . . . • • . . . .' · Logical Names File Organizntion · . Record Access · RECORD FORMATS . . . · Fixed-Length Records . • . • . Variable-Length Records . . . . . · • THE CLOSE PROCEDURE · THE FIND PROCEDURE . . • . . • . THE GET PROCEDURE • . . • THE LINE LIMIT PROCEDURE THE OPEN PROC EDURE • • . . . . . . File History -- NEW, OLD, RE~DONLY, or UNKNOWN Record Length . . . • • • • . . Record Access Mode -- SEQUENTIAL or DIRECT Record Type -- FIXED or VARIABLE . . . . Carriage Control -- LIST, CARRIAGE, or NOCARRIAGE . . . . • • • . • • • . Examples . . . • . THE PAGE PROCEDURE • THE PUT PROCEDURE THE READ PROCEDURE THE READLN PROCEDURE . THE RESET PROCEDURE THE REWRITE PROCEDURE • • . • . THE WRITE PROCEDURE THE WRITELN PROCEDURE • • . . TERMINAL I/O • • . • • • . · . . . . . . . · · · 7-2 7-2 7-3 7-3 7-3 7-4 7-4 7-4 7-4 7-0 7-7 7-8 7-10 7-10 7-10 7-11 7-11 7-12 7-14 7-15 7-10 7-18 7-19 7-20 7-21 7-25 7-28 USING PASCAL ON TOPS-20 PROGRAM DEVELOPMENT PROCESS . 8-1 FILE SPECIFICATIONS AND DEFAULTS • 8-2 CREATING A PROGRAM • . . • . 8-3 COMPILING A PROGRAM • • • . • . . . . 8-4 The PASCAL Command • • • • . • • • • • • . • 8-4 PASCAL Compiler Commands • • • • • . . • • • . . 8-5 PASCAL Compiler Switches. • . . • • • . . • 8-6 Specifying Switches in the Source Code. • 8-9 Specifying Output Files • • • . 8-11 Compiler Listing Format • • • • . 8-11 Source-Code Listing 8-14 Machine-Code Listing • •••. 8-15 Cross-Reference Listing 8-10 LOADING A PROGRAM 8-16 The LOAD Command • • • • • • . • • • 8-16 EXECUTING A PROGRAM . • • • 8-17 EXAMPLES. • • • • • 8-17 PASDDT: THE PASCAL-20 DEBUGGER RUNNING PASDDT USING SYMBOLIC VALUES SCOPE • • • • PASDDT COMMANDS ASSIGN • BREAK • • • • CLEAR • • • • DISPLAY • • • • • • • • EXIT • • • • • • • • • • • • HELP • • • ••••• • PROCEED • • • • • • • • v • • • 9-1 9-1 • 9-2 9-3 • • • 9-3 • • • 9-4 • 9-6 • • 9-7 • • 9-9 9-10 9-10 9.4.8 9.4.9 9.4.10 9.4.11 9-11 9-11 9-14 9-15 REMOVE • SET SHOW • • TRACE APPENDIX A PASCAL .MESSAGES APPENDIX B ASCII CHARACTER SET APPENDIX C SYNTAX SUMMARY C.l BACKUS-NAUR FORM . . • . • • • . • • • • • • • • • C-l APPENDIX D SUMMARY OF PASCAL-20 EXTENSIONS TO PROPOSED ISO STANDARD APPENDIX E ISO COMPLIANCE E.l E.2 E.3 E.4 IMPLEMENTATION-DEFINED FEATURES IMPLEMENTATION-DEPENDENT FEATURES ERROR HANDLING . . • . • . • EXCEPTIONS AND RESTRICTIONS • • • • E-l • • E-3 • • • • • E- 3 • • • APPENDIX F DIFFERENCES BETWEEN PASCAL-20 AND VAX-II PASCAL APPENDIX G PROCEDURE AND FUNCTION CALLING SEQUENCES G.l G.2 G.3 G.l.1 G.3.2 G.3.3 G.3.4 G.l.5 G.4 G.t) RUN-TIME STACK . . • • • . • . . • • MECHANICS OF A PROCEDURE CALL PARAMETER PASSING Value Parameter Passed By Value ••.. Value Parameter Passed By Address Reference (VAR) Parameter .•.• • Procedure Or Function Parameter • Conformant Array Parameter. • • PARAMETER ACCESSING EXAMPLE CONFORMANT ARRAY EXAMPLE • . • • • • • • • E-8 • • . • G-l • • G-2 • • • G- 3 G-3 · G-3 • • • • • • • • • • • • • G-4 • G-4 • G-4 • G-5 INDEX • G- 5 Index-l FIGURES FIGURE 1-1 1-2 2-1 2-2 2-3 3-1 4-1 7-1 7-2 8-1 9-1 Structure of a PASCAL Program %TNCLUDE File Levels • . . . . . Two-DimensionaJ Array Two D Three-Dimensional Array ChesslD Storing Components in an Array Scope of Identifiers • . . . . • . PASCAL Data Types ..•• File Position After GET ...• File position after RESET Compiler Listing Format ..•.•. Scope . . . . . • . . . . . . vi · . • • . . • • • 1- 3 1-12 . 2-9 2-10 2-11 • 1- 8 · 4-5 · 7-6 7-19 8-12 . . · . • • . 9-2 G-l G-2 G-3 G-4 Status of Stack After PUSHJ Stack Frame •.•..... External Proce~ure Declaration . Conformant Array Parameter . . . · G-1 • • G-2 · • G-5 · G-6 · • TABLES TABLE 1-1 1-2 1-3 3-1 3-2 3-3 3-4 3-5 3-6 6-1 6-2 f)-3 7-1 7-2 7-3 7-4 8-1 8-2 8-3 8-4 A-I A-2 B-1 C-l F-I F-2 Feserved Words • . . . . • Predeclared Identifiers Special Symbols •. . . • • Arithmetic Operators . . . • Result Types for Arithmetic Expressions Relational Operators . Logical Operators t:e tOpe ra to rs Precedence of Operators Predeclared Procedures. Predeclared Functions Library Routines • Default Values for TOPS-20 External File Specifications • • • • . • Summary of File Attributes Default Values for Field Width . Carriage-Control Characters · File Specification Defaults PASCAL Compiler Commands • . . • . • PASCAL Compiler Switches. · Source Switches .••.• • • • • Run-time Errors .•..•••• I/O Errors • . • . • • . The ASCII Character Set • • • • • BNF MetaSymbols ••• . Additional Language Elements • • Additional Predeclared Functions • • vi i I-f) • • 1-7 • • • . . 1- 8 • • • . • 1-2 · 1-3 · 1-4 • • • 3-5 • 3- 5 · 3-6 · • • • fi-2 f)-13 fi-17 • 7-9 · · • • . • • • • • . • 7 -12 7-22 7 -26 · 8-3 • • • • • • · • • • 8-5 • 8-7 8 -10 · A-I A-2 • • • • • . . . • B-1 . C-l • • • • • • • • • • F- 4 F- 2 PREFACE MANUAL OBJECTIVES This manual describes the PASCAL language and the PASCAL ctebugger, PASDDT, as they are implemented on the TOPS-20 operating system. This document is designed primarily for reference; it is not a tutorial document. INTENDED AUDIENCE This manual is intended for readers who know the PASCAL language. The reader need not have a detailed understanding of the TOPS-20 operating system, but some familiarity with either is helpful. For information about the TOPS-20 operating system, refer to the documents listed below under "Associated Documents." For introductory information about the use of the PASCAL language, refer to the TOPS-20 PASCAL Primer, Order Number AA-L3l4A-TM. STRUCTURE OF THIS DOCUMENT This manual contains the following chapters and appendixes: • Chapter 1 provides an introduction to the use of describes the format of a PASCAL program. PASCAL • Chapter 2 introduces basic concepts including variables, data types, expressions, and scope. constants, • Chapter 3 describes the components of an expression. • Chapter 4 section. • Chapter 5 describes the statements that perform of the program. • Chapter ~ explains the use of functions and procedures, and summarizes the predeclared functions and procedures supplied with the PASCAL-20 language. • Chapter 7 provides detailed information on input procedures. • Chapter 8 describes the compiling, loading, and executing PASCAL programs on the TOPS-20 operating system. • Chapter 9 describes the PASCAL-20 debugger, PASDDT. describes the program ix heading an~ and declaration the and actions output of • Appendix A lists the various messages you can receive. • Appendix B lists the ASCII character set. • Appendix C presents the PASCAL-20 language in the Backus-Naur form and includes syntax diagrams. • Appendix D summarizes PASCAL-20 language. • Appendix E describes how PASCAL-20 complies with the standard proposed by the International Standardization Organization (ISO) . • Appendix F summarizes the differences between TOPS-20 and VAX-li PASCAL. • Appendix G describes the calJing sequences and conventions used by PASCAL for user-defined procedures and functions. the extensions ASSOCIATED DOCUMENTS Associated manuals are: • • • TOPS-20 PASCAL Primer --TOPS-20 User's Guide ---- --TOPS-20 Commands Reference Manual • LINK Reference -Manual --• • EDIT Reference Manual --TV Editor Manual x incorporated in the PASCAL CONVENTIONS USED IN THIS DOCUMENT This document uses the foJlowing conventions: Convention Meaning A horizontal ellipsis means thnt the preceding item can be repeated one or more times. A vertical ellipsis means that not all of the statements in a figure or example are shown. [ ] Double brackets in statement and declaration format descriptions enclose optional items, for examp] e: WRITE r ] ([OUTPUT,] print-list) Square brackets show where the syntax requires square brackets. This notation is used with arrays, for example: ARRAyrl •• 5] OF INTEGER { } Braces enclose lists from which choose one item, for example: you must This symbol indicates RETURN key. press the where you <CTRL/x> The notation <CTRL/x> indicates that you must press the key labeled CTRL while simultaneously pressing another key (x), for example, <CTRL/Z>. UPPERCASE LETTERS Uppercase letters in a command Jine indicate information that you must enter as shown. lowercase letters Lowercase letters in a command line variable information you supply. Simple_Procedure In programming examples, all identifiers, (names created by the programmer), are printed in lowercase letters with initial capitals. Contrasting Colors Orange - where examples contain both user input and computer output, the characters you type are in orange; the characters printed on the terminal are in black. xi indicate CHAPTER I INTRODUCTION PASCAL-20 is an extended implementation of level 1 of the standard proposed for the PASCAL language by the International Standardization Organization (ISO). This manual describes the use of PASCAL under the TOPS-20 operating system. PASCAL-20 includes all the language elements as defined in the PASCAL User Manual and Report by Jensen and Wirth, as well as the following extensions: • Exponentiation operator • Hexadecimal, octal, and binary integers • Double-precision real data type • Dollar sign ($) • External procedure and function declarations • CARD, CLOCK, EXPO, SNGL, and UNDEFINED functions • REM operator • OTHERWISE clause in the CASE statement • OPEN and CLOSE procedures for file access • FIND procedure for direct access to sequential files • Optional carriage control for output files • DATE, TIME, HALT, and LINELIMIT procedures • Variable initialization • Separate compilation • %INCLUDE directive compilation • Support Eor calling externally declared FORTRAN subroutines, and for declaration of PASCAL subroutines that can be called by FORTRAN and underline ( ) characters in identifiers alternate for input files during Refer to Appendix E for more information on ISO compliance. This chapter presents an overview of the important concepts in PASCAL and illustrates the structure of a PASCAL program. It also describes PASCAL's lexical elements the character set, reserved words, identifiers, and special symbols. The final sections explain how to document your program and how to include existing files. 1-1 INTRODUCTION 1.1 OVERVIEW OF PASCAL A PASCAL program performs operations on data items known as constants, variables, and function designators. A constant is a quantity with an unchanging value. A constant to which you give a name is called a symbolic constant. A variable is a quantity whose value can change while the program executes. A function designator causes the execution of a group of statements that is associated with an identifier and returns a value. The function type is determined by the type of the value it returns. 1.1.1 Data Types Every PASCAL data item is associated with a data type. A data type, which is usually indicated by a type identifier, determines both the range of values a data item can assume and the operations that can be performed upon it. In addition, the type implicitly indicates how much storage space is required for all possible values of the data item. PASCAL provides identifiers for many predefined types. Thus, a program's operations can involve integers, real numbers, Boolean and character data, arrays, records, sets, and pointers to dynamic variables. PASCAL also allows you to create your own types by defining an identifier of your choice to represent a range of values. The type of a constant is the type of its corresponding value. You establish variable and function types when you declare them. In general, they cannot change. Although variables and functions can change in value any number of times, all the values they assume must be within the range established by their type. A variable does not assume a value until the program assigns it one. A function is assigned a value during its execution. PASCAL associates types not only with data items, but also with expressions. An expression is the computation of a value resulting from a combination of variables, constants, function designators, and operators. In PASCAL, you can form expressions using arithmetic, relational, logical, string, and set operators. Arithmetic expressions produce integer or real number values. Relational, logical, string, and most set expressions yield Boolean results. Other set expressions form the union, intersection, and differences of two sets. 1.1.2 Structure of a PASCAL Program A PASCAL program consists of a heading and a block. The heading specifies the name of the program and the names of any external files the program may use. The block is divided into two parts: the declaration section, which contains data declarations; and the executable section, which contains executable statements. Figure 1-1 points out each part of a sample PASCAL program. 1-2 INTRODUCTION PROGRAM Calculator (INPUT, OUTPUT); TYPE Yes_No = (Yes, No); VAR Subtota 1, OpeT'arld ! REAL.; EGuatior. ! BOOL.EAN; Ope T'ato T' ! CHAR f AnsweT' ! Ye!:; .... No ji Declaration Section PROCEDURE InstT'ucticms; BEe, IN WFn TEL N (' This pro g r a ITI add s, sub t T' act s, lTIul tip 1 i e s, and'); WRITEL.N ('divides real nUlTlbers. Enter a nUlTlber in response'); WRITELN ('to the Operand! prolTlPt and enter an operator -- '); Procedure WRITELN ( ' t f -, *, /, or = -- in response to the Operator!'); Block WRITELN ('proITlPt. The progralTl keeps a running subtotal'); WRITELN ('until ~ou enter an e~ual sign (=) in response to'); WRITELN ('the Operator! prolTlPt. You can then exit frolTl'); WF~ I TEl... N (' t h €-! F' T' 0 ~.;! T' a ITI 0 I' b f::' !:.I ina new s f~ t 0 f cal c 1•.11 at i C) n!:; • ' ) ; ENI; (*end of procedure Instructions*) BEGIN WRITE ('Do YOU need instructions? r~pe yes or no. RFADl..N (An~; we Y') ; If Answer = Yes THEN Instructions; '); F~FF'EAT EC~l..Iat:i.on !"" FAL~:;F; Subtota 1 : :: .. 0; WR I TE (' ClF'e rand! ' ) ; READLN (Subtotal); WHILE (NOT [~uation) DO BEGIN WRITE ('Operator!'); READLN (Operator); IF (Operator = '=') THEN BEGIN E~uation != TRUE; WRITELN ('The answer is ',Subtotal!5!2) END ELSE BEGIN WRITE ('Operand!'); READLN (Operand); CASE Operator OF Subtotal _. Subtotal + Operand; '+ ' '- , Subtotal ' .- Subtotal - Ope T'and; ,- Subtotal * Operand; Subtotal ,'*' IIi Subtotal ,-- Subtotal / Operand END; WRITELN ('The subtotal is ',Subtotal!5!2) END END; Executable Section ..... WRITE ('An~ more calculations? READLN (Answer); UNTIL Answer = No; END. Figure 1-1: T~pe ~es or no.'); MR·S-3150-83 Structure of a PASCAL Program 1-3 INTRODUCTION Procedure and function declarations have the same structure as programs. Note, in Figure 1-1, the heading and block of the procedure instructions. This manual uses the term subprogram to denote a procedure or function. 1.1.3 Definitions and Declarations PASCAL requires you to define every constant and user-created type and to declare every label, variable, procedure, and function used in your program. The declaration section of the program contains LABEL, CaNST, TYPE, VAR, VALUE, PROCEDURE, and FUNCTION sections, in which you define and declare all the data your program uses. All of these except LABEL introduce identifiers and indicate what they represent. LABEL declares numeric labels that correspond to executable statements accessed by the GOTO statement. PASCAL allows you to assign initial values to variables you declare in a VAR section. An initialized variable assumes the given value when program execution begins. 1.1.4 Executable Statements The executable section of a PASCAL program contains the statements that specify the program's actions. The executable section is delimited by the reserved words BEGIN and END. Between BEGIN and END are conditional and repetitive statements, statements that assign values to variables and functions, and statements that control program execution. 1.1.5 Subprograms PASCAL provides several ways for you to group together definitions, declarations, and executable statements. One way is to group them into procedures and functions, generically called subprograms. Both kinds of subprograms are groups of statements associated with an identifier. Procedures are usually written to perform a series of actions, while functions are written to compute a value. Subprograms constitute a convenient way to isolate the individual tasks that the main program is to accomplish. Subprograms do not exist independently of the program; they are called either by an executable statement known as a procedure call or by a function designator appearing within an expression. PASCAL supplies many predeclared subprograms that perform commonly used operations, including input and output. A subprogram consists of a heading and a block. The heading provides the name of the subprogram, usually a list of formal parameters that declare the input data for the program, and, in the case of functions, the type of the result. The subprogram block consists of an optional declaration section and an executable section. When the declaration section is present, it declares data that is local to the routine (that is, data that is unavailable outside the subprogram). PASCAL is a block-structured language in that it allows you to nest subprogram blocks not only within the main program, but also within other subprograms. Each subprogram can make its own local definitions and declarations and can even redeclare an identifier. that has been declared in an outer block. A subprogram declared at an inner level has access to the declarations and definitions made in all blocks that enclose it. 1-4 INTRODUCTION 1.1.6 Compilation Units A program is sometimes calJed a compilation unit in this manual because it can be compiled as a single unit (unlike a subprogram, which cannot be compiled without the context of a program). A program consists of a heading and a block, just as a subprogram does. The heading consists of the name of the program and possibly a list of identifiers to indicate any external files that the program uses. The declaration section of the program block declares data that is available at all program levels, including all nested subprograms. 1.2 LEXICAL ELEMENTS A PASCAL program is composed entirely of lexical elements. These elements can be individual symbols, such as arithmetic operators; or they can be words that have special meaning to PASCAL. The basic unit of any lexical element is a character, which must be a member of the ASCII character set, as described in section 1.2.1. Some characters are special symbols that PASCAL uses as statement delimiters, operators, and elements of the language syntax. Special symbols are listed in Section 1.2.4. The words that PASCAL uses are combinations of alphabetic characters and occasionally a dollar sign (~;), an underscore ( ), or a percent sign (%). PASCAL reserves some words for the names of executable statements, operations, and some of the predefined data types. Reserved words are listed in Section 1.2.2. Other words in a PASCAL program are called identifiers. Predefined identifiers represent routines and data types provided by PASCAL. Other identifiers can be created by you to name programs, constants, variables, and any other necessary program segment that is not already named. Section 1.2.3 explains the use of both kinds o~ identifiers. 1.2.1 Character Set PASCAL uses the full American Standard Code for Information Interchange (ASCII) character set (see Appendix B). The ASCII character set contains 128 characters in the following categories: • The uppercase and lowercase letters A through Z and a through z • The numbers 0 through 9 • Special characters, such as ampersand (&), question mark (?), and equal sign (=) • Nonprinting characters, such carriage return, and bell 1-5 as space, tab, line feed, INTRODUCTION The PASCAL compjler does not distinguish between uppercase and lowercase characters, except in character and string const~nts and the values of character and string variables. For example, the reserved word PROGRAM has the same meaning when written as any of the following: PROGRAM PRogrAm pro ~.=.1 r a III The constants below, however, represent different characters: ,b ' ,BI The following two constants represent different strings: 'BREAD AND ROSES' 'Bread and Roses' 1.2.2 Reserved Words PASCAL reserves the words in Table 1-1 as names for statements, data types, and operators. This manual shows these words in uppercase characters. Table 1-1: Reserved Words AND ARRAY BEGIN CASE CONST DIV DO DOWNTO ELSE NIL NOT OF OR PACKED PROCEDURE PROGRAM RECORD REPEAT END FILE FOR FUNCTION GOTO IF IN LABEL MOD SET THEN TO TYPE UNTIL VAR WHILE WITH You can use reserved words in your program only in the contexts in which PASCAL defines them. You cannot redefine a reserved word for use as an identifier. In PASCAL, the following words are considered semi reserved words: MODULE OTHERWISE REM VALUE Like the words. for your used for they are reserved words, PASCAL also predefines these semi reserved However, unlike reserved words, you can redefine these words own purposes. If you redefine them, they can no longer be their original purpose within the scope of the block in which redefined. I-f) INTRODUCTION 1.2.3 Identifiers PASCAL uses the term identifier to mean the name of a program, module, constant, type, variable, procedure, or function. An identifier is a sequence of characters that CRn include letters, digits, dollar signs ( $ ), and un de r 1 i n e s ym b 0 1 s ( ), wit h the foIl ow i ng res t ric t ion s : • An identifier can begin dig it. with any character • An identifier must be unique in its first within the block in which it is declared. • An identifier must not contain any blanks. other 31 than a characters PASCAL places no restrictions on the length of identifiers, but scans only the first 31 characters for uniqueness; the rest are ignored. ~he following are examples of valid and invalid identifiers: Va 1 id Invalid Fo r2n8 Max Words Upto $CREMBX 4awhile (starts with a digit) Up&to (contains the ampersand) 1.2.3.1 Predeclared Identifiers - PASCAL predeclares some identifiers as names of functions, procedures, types, values, and files. These predeclared identifiers are listed in Table 1-2 and appear in uppercase characters throughout this manual. Table 1-2: ABS ARCTAN BOOLEAN CARD CHAR CHR CLOCK CLOSE COS DATE DISPOSE DOUBLE EOF EOLN Predeclared Identifiers -----EXP EXPO FALSE FIND GET HALT INPU1r INTEGER LINELIMIT LN MAXINT NEW ODD OPEN ORD OUTPUT PACK PAGE PRED PUT READ READLN REAL RESET REWRITE ROUND SIN SINGLE SNGL SQR SQRT SUCC TEXT TIME TRUE TRUNC UNDEFINED UNPACK WRITE WRITELN ------ You can redefine a predeclared identifier to denote some other item. Doing so, however, means that you can no longer use the identifier for its usual purpose within the scope of the block in which it is redefined. READ For example, the predeclared identifier READ denotes the procedure, which performs input operations. If you use the word READ to denote something else, such as a variable, you cannot use the READ procedure. Because you could lose access to useful language features, you should avoid redefining predeclared identifiers. 1-7 IN'rRODUCTION The directives FORTRAN, FORWARD, EXTERN, and EXTERNAL are also predeclared by the PASCAL compiler. However, they retain their meanings as directives even if you redefine them as identifiers. 1.2.3.2 User Identifiers - User identifiers denote the names of programs, modules, constants, variables, procedures, functions, and user-defined types. User identifiers name all significant data structures, values, and actions that are not represented by a reserved word, predeclared identifier, or special symbol. 1.2.4 Special Symbols Special symbols represent arithmetic, relational, and set operators, delimiters, and other syntax eJements. PASCAL includes the special symboJs listed in Table 1-3. Table 1-3: Special Symbols Name Symbol Name Plus sign + Period Equal Multiplication * < Not equal <> Less than Exponentiation ** Colon Subrange ope ra to r Comma Parentneses ( Comment ( * *) ) Minus sign Square brackets I' Division / Greater than > <= Semicolon Assignment operator .= Pointer Greater than or equal >= Less equal 1.3 than Symbol or " 1 ( . .) @ DELIMITERS PASCAL uses two special symbols as delimiters: the semicolon (;) and the period (.). The semicolon separates one PASCAL statement from the next. One line of your program can contain one or many statements, Th.e period marks but the statements must be separated by semicolons. the end of the PASCAL program. 1-8 INTRODUCTION The semicolon and the period are the only characters that PASCAL recognizes as delimiters. Spaces, tabs, and carriage-return/line-feed combinations are separators and cannot appear within an identifier, a number, or a special symbol. You must use at least one separator between consecutive identifiers, reserved words, and numbers; but you can use more than one if you want. You could, for instance, put each element of a PASCAL program on a separate line: r-f<OGf<AM ~:; i IYt ( OUTPUT) BEGIN Wr:~ITEL..N 'This is a slmple pro~ralYt.' END. You could also put the entire program on one line: PROGRAM Sim(OUTPUT);BEGIN WRITELN('This is a simple pro~ram.')END. As long as each complete statement is separated from the next by a semicolon, PASCAL interprets your input correctly. However, including spaces, tabs, and carriage-return/line-feed combinations make your program easier to read and understand. For readability, you could write it as follows: PROGRAM Sim (OUTPUT); BEGIN WRITELN(JThis is a simple END. pro~ram.') The reserved words BEGIN and END are also used as delimiters. BEGIN indicates the start of the executable section or a compound statement, and need not be followed by a semicolon. END indicates the end of one of the following: • A record definition • An executable section • A compound statement • A CASE statement (see Section 5.3.3) Although PASCAL does not require one, you can use a semicolon immediately before END. A semicolon in this position results in an empty statement between the semicolon and the reserved word END. The empty statement implies no action. 1.4 DOCUMENTING YOUR PROGRAM In addition to statements and delimiters, you can put comments in your PASCAL program. Comments are simply words or phrases that describe what happens in the program. You can enclose comments in braces { }, as follows: < This is a comment. } 1-9 INTRODUCTION Also, you can start a comment with the left-parenthesis/asterisk character pair, ano end it wi th the asterisk/right-parenthesis character pair, as follows: (* This is also a comment *) You can also mix the type of comment characters you use. For example, you can use a left brace with an asterisk/right-parenthesis character pair: { This is another comment *) You can place a comment anywhere a space is legal. comments are not delimiteo by semicolons. Unlike statements, A comment can contain any ASCII character because PASCAL text of the comment. ignores the NOTE To turn off braces as recognized comment characters, use the /NATIONAL switch. See Section 8.4.3 for more information on thjs switch. 1.5 THE %INCLUDE DIRECTIVE The %INCLUDE directive allows you to ~ccess statements from a PASCAL file, calJed the included file, during compilation of the current file. The contents of the included file are inserted in the place where the PASCAL compiler finds the directive. This directive can appear anywhere in the PASCAL program. Format /L IST %INCLUDE 'file specification [{ /NOLIST }ll' n where: 'file specification' is the name of the file to be The apostrophes are required. /LIST indicates that the included file is to be printed in the listing. This is the default. /NOLIST indicates the included file is not to be printed in the listing. included. When the compiler finds the %INCLUDE directive, it stops reading from the current file and begins reading from the included file. When the compiler reaches the end of the included file, it resumes compilation immediately following the %INCLUDE directive. This directive can appear wherever a comment can appear. An included file can contain any PASCAL declarations or statements. However, the declarations in an included file, when combined with the other declarations in the compilation, must follow the required order for declarations. 1-10 INTRODUCTION In the following example, the %INCLUDE directive specifies CONDEF.PAS, which contains constant declarations. Main P~SCAL file Program PROGRAM Student_Courses (INPUT, OUTPUT, CON!:>T %INCLUDE TYPE the SCHED)~ 'CONDEF. PAb' Schf.~du 1. (.:."~;) r.:ECOF~D Yeal"' : ( F r', S D, ..J r 1I S r' ) , PACKED ARRAY [1 •• 30] OF CHAR, F'aY'(~nts PACKED ARRAY [1 •• 40] OF CHAR; Collc~~ge : (Eng i nC·:."f;' r i n!:j" Arch i tectu r'(-:~, A~~ r i cuI tl.H'f:~) E:ND; NalTlE.\ : External File CONDEF.P~S MAX .... CLASS :::: 300; N._PROFS :~ 140; FROS~'I :::: 3000; The %INCLUDE directive instructs the compiler to insert the contents of the file CONDEF.PAS after the reserved word CONST in the main program. The main program Student Courses is compiled as if it contained the following: PROGRAM Student_Courses (INPUT, OUTPUT, SCHED); CaNST Max_Class = 300, N_.P T'ofs = 140; Frosh ::.: 3000; TYPE Schedules = RECORD Year: (Fr, SQ, Jr, Sr); Name: PACKED ARRAY [1 •• 30) OF CHAR; Parents PACKED ARRAY [1 •• 40) OF CHAR, College : (Engineering, Architecture, Agriculture) END; You can use the %INCLUDE directive in another included file; however, recursive %INCLUDE directives are not allowed. If, for example, the file OUT.PAS contains an %INCLUDE directive for the file IN.PAS, then IN.PAS must not contain an %INCLUDE directive for the file OUT.PAS. l-Ll INTRODUCTION An included file at the outermost 1evel of a program is sa id t.o be included at the first leve1. A file included by a first-level included file is at the second level, and so on. There is no limit to Figure 1-2 the number of included files you can nest in a program. illustrates some levels of included files. Main Program A.PAS F' T'()~1 rail! p, CON~:)T VAR %INCLUDE 'C.PAS' (* Both Level 2 *) TYF'E %INCL..UDE 'A.PAS' (* LE:.\V0~1 :L ZINCL..UDE 'B.F'AS' *) C.Pl\S D.PAS VAR ZINCLUDE 'D.PAS' (* L..evfd 3*) FUNCTION ZINCL..UDE ~E.PAS' PROCEDURE ZINCL..UDE 'F.PAS' <* Both Level 4 *) F.PAS G.PAS FUNCTION ZINCL..UDE 'G.PAS' Figure 1-2: %INCLUDE File Levels 1-12 CHAPTER 2 PASCAL DATA TYPES This chapter describes PASCAL data types and how to define and declare them in the TYPE and VAR sections of a PASCAL program. This chapter also provides general information about using each data type. PASCAL uses three categories of data types: 1. Scalar 2. Structured 3. Pointer Scalar data types represent ordered groups of values. The scalar data types, which are described in Section 2.2, consist of predefined and user-defined data types. Predefined data types include integers, real numbers, and characters. User-defined datn types include a range of explicitly defined values and a subrange of another data type. Scalar data types are building blocks for the structured data types. Structured data types are collections of data types organized in specific ways. Structured data types include arrays, record files, and sets. These are described in Section 2.3. Pointer data types provide access to dynamic are described in Section 2.4. 2.1 data structures. They DECLARING DATA TYPES PASCAL provides two methods of declaring variables of a particular type. You can define the type in the TYPE section, and then use a declaration in the VAR section to declare one or more variables of the newly defined type. The general format is: TYPE type identifier = type definition; VAR variable name: type identifier; Alternatively, you can declare a variable by specifying the type definition in the VAR section and omitting the type identifier and type definition from the TYPE section. The general format for this method is the following: VAR variable name type definition; If a data ~ype is used only once within the program, it is simpler define it In the VAR section. 2-1 to PASCAL D~TA TYPES If a data type is used more than once in the program, it is more efficient to define the data type within the TYPE section. This creates a structure that can be accessed by more than one identifier. For example, if a program uses an array three times, you can define the array type in the TYPE section, and assign three identifiers to that array type in the VAR section. 2.2 SCALAR TYPES Scalar data types consist of ordered sets of values with the concept of predecessor and successor. For example, the scalar data type INTEGER represents whole numbers that follow in a predefined sequence: 5 is less than 300. Scalar data types encompass two subclasses: predefined and user-defined. These are described in the following sections. 2.2.1 Predefined Data Types PASCAL provides the following predefined scalar data types: 1. INTEGER 2. REAL 3. SINGLE 4. DOUBLE 5. BOOLEAN 6. CHAR The predefined types SINGLE and DOUBLE provide explicit single-precision and double-precision real numbers. Throughout this manual, the term REAL refers to REAL, SINGLE, and DOUBLE types. The following sections describe each predefined data type. 2.2.1.1 INTEGER Data Type - The type INTEGER denotes positive and negative whole number values ranging from (-2**35) to (+2**35)-1, or -34359738368 to +34359738367. The largest possible value of the INTEGER data type is known by the predefined constant identifier MAXINT. You can indicate a decimal integer combined with plus and minus signs. constants in PASCAL: constant with decimal digits The following are valid decimal 17 -333 o +1 89324 A minus sign (-) must precede a negative integer value. A plus sign (+) may precede a positive integer, but the sign is not required. No commas or decimal points are allowed. 2-2 PASCAL DATA TYPES In addition to decimal notation, PASCAL allows you to specify integer constants in binary, octal, and hexadecimal notation. You can use constants written in these notations anywhere that decimal integer constants are permitted. To specify an integer constant in binary, octal, or hexadecimal notation, place a percent sign (%) and a letter in front of a number enclosed in apostrophes. The appropriate letters, which can be either uppercase or lowercase, are B for binary notation, 0 for octal notation, and X for hexadecimal notation. An optional plus or minus sign can precede the percent sign to indicate a positive or negative value. Note that regardless of which notation you use, the value can not exceed MAXINT, for example: -%B'111001' %b'10000011' %0'7712' -%0'473' +%X'53Al' -%x'DEC' 2.2.1.2 REAL Data Type - The reserved words REAL, SINGLE, and DOUBLE denote the real number types. In PASCAL, a real number can range from +-0.14*10**-38 through +-3.4*10**38, with a typical precision of eight decimal digits. REAL and SINGLE are synonymous; both have single-precision real number va]ues. The type DOUBLE allows you to declare double-precision real variables. You can assign real and integer values to a variable of type REAL, SINGLE, or DOUBLE. If you assign an integer value to a variable of type REAL, PASCAL converts the integer to a real number. In a PASCAL program, you can write real numbers in two ways; fixed on floating point. With fixed point notation, you write the number with the decimal point exactly where it appears in the value. The first way is the following form: 2.4 893.2497 -0.01 8.0 -23.18 0.0 Note that, in this form, at least one digit must appear on each side of the decimal point. That is, a zero must always precede the decimal point of a number between 1 and -1, and a zero must follow the decimal point of a whole number. Some numbers, however, are too large or too small to write conveniently in the above format. PASCAL provides scientific (also known as exponential) notation as a second way of writing real numbers. In scientific notation, you write the number as a positive or negative value followed by an exponent, for example: 2.3E2 -0.07E4 10.0E-1 -201E+3 -2.14159£0 2-3 PASCAL DATA TYPES The letter E after the value means that the value is to be multiplied by a power of 10. Note that you can use an uppercase or lowercase the power of 10; the letter. The integer following the E gives integer can be positive or negative. Using scientific notation, you can write the real number 217.0 in any of the following ways: 237E'O ::.~. ::~7E2 O.000237E+6 2370E····1 O.()()00000237E10 This format is often called floating-point format because the implied position of the decimal point "floats" depending on the exponent following the E. At least one digit must appear on each side of the decimal point, if the decimal point is present. PASCAL provides single and double-precision representation for real numbers. Single precision typically provides eight significant digits, depending on the magnitude of the number. Double precision extends the number of significant digits to 18. To indicate a double-precision value, you must use floating-point notation, replacing the letter E with an uppercase or lowercase D, for example: ono 4. 371 ~7j2Bf.)65D··"3 --812d2 4[1··-3 The integer following the D is an exponent, as in single-precision floating-point numbers. All the above values have approximately 18 significant digits. 2.2.1.3 BOOLEAN Data Type - BOOLEAN data types can have the value TRUE or FALSE. Boolean values are the result of testing expressions for truth or validity. The result of a relational expression (for example, A < B) is a Boolean value. PASCAL defines Boolean data types as predefined identifiers and orders them so that FALSE is less than TRUE. For assignment purposes, the type BOOLEAN is compatibJe with those variables and expressions that yieln a BOOLEAN result. 2.2.1.4 CHAR Data Type - The value of data type CHAR is a single value from the ASCII character set, as listed in Appendix B. To specify a character value, enclose an ASCII character in apostrophes. The apostrophe character itseJf must be typed twice within apostrophes. Each of the following is a valid character value: 'A' , z" . '0' , , ,,,, '? ' 2-4 PASCAL DATA TYPES You can use strings such as 'HELLO' and '****', but you must represent them as packed arrays of characters (see Section 2.3.1.2). When you use the ORD function in an expression of type CHAR, the result is the ordinal value in the ASCII character set of the character value. See Section 2.2.2.3 for an explanation of the ORD function. 2.2.2 User-Defined Scalar Data Types User-defined scalar data types are those that you define, as opposed to those data types that PASCAL predefines for you. PASCAL allows you to define two kinds of scalar data types: enumerated and subrange. An enumerated type consists of an ordered list of identifiers. The subrange type is a continuous range of values of a defined scalar type, called a base type. The following sections describe these two user-defined types. 2.2.2.1 Enumerated Data Types - An enumerated data type is an ordered list of identifiers. To define an enumerated type, list in some order all the identifiers denoting its values. With PASCAL, you can define an enumerated data type in two ways: Fo rma t I TYPE identifier (identifier II,identifier, •.• ] ) (identifier I[ ,identifier, •.• ] ) Fo rma t 2 VAR identifier where: identifier is the name of the enumerated type. For example: TYPE Beverage = (Milk, Water, Cola, Beer); This TYPE section defines the type Beverage and lists all that Beverage can assume within a program. the values PASCAL assigns an order to the items in your list from left to right. Thus, the values of an enumerated type follow a left-to-right order, so that the last value in the list is greater than the first, for example: TYPE Seasons = (Spring, Summer, Fall, Winter) , The relational expression (Spring < precedes Fall in the list of values. Fall) is TRUE because Spring The only restriction on the values of an enumerated type is that you cannot define the same value in more than one list in the same TYPE section. For example, the following is illegal: TYPE Seasons = (Spring, Summer, Fall, Winter) School~ear = (Fall, Winter, Spring); 2-5 PASCAL DATA TYPES To initialize a variable of an enumerated type, specify a constant value. For example, you can assign the variable Quarter of type Seasons as follows: VAR Quarter: Seasons:= Fall; The variable Quarter takes on the initial va]ue Fall. Examples TYPE ColoY's "~.(Rf:~(h Ypllow, Gret~r" Purple, Blue); Sport = (Swim, Run, Ski); Beverage = (Milk, Water, Colay Beer); VAR Cookie: (Oatmeal, Choc-Chipy Peanut-Butter, Exercise, Fun: Sport:= Ski; Drink: Bevera~e; Su~ar) The TYPE section defines the types Colors ann Sport, listing values that variables of each type can assume. := Su~ar; all the The VAR section declares the variable Cookie, which can have the values Oatmeal, Choc-Chip, Peanut-Butter, and Sugar. The variables Exercise and Fun are declared as type Sport, and Drink is declared as type Beverage. Initial values are established for the identifiers and Fun in the VAR section. Cookie, Exercise, 2.2.2.2 Subrange Data Types - A subrange specifies a limited portion of another scalar type (called the base type) for use as a type. Fo rma t 1 TYPE identifier lower limit •• upper limit Format 2 VAR identifier lower limit •• upper limit where: identifier is the name of the subrange. lower limit is the constant subrange. value at the low end of the end of the separates the limits of the subrange. upper limit is the "constant value subrange. at the high The subrange type is defined only for the values between and including the lower and upper limits. The limits you specify must be constants; they cannot be expressions. (See Chapter 3 for information on expressions.) The values in the subrange are in the same order as in the base type. 2-6 PASCAL DATA TYPES The base type can be any enumerated or predefined scalar type except REAL. You can use a subrange type anywhere in the program where its base type is legal. The rules for operations on a subrange are the same as the rules for operations on its base type. A subrange and its base type are compatible. The use of subrange types can make a program clearer. For example, integer values for the days of the year range from 1 to 365. Any value outside this range is obviously incorrect. You could specify an integer subrange for the days of the year as fo]lows: VAF: Da~,~····Of···· y €·~a r J •• 366 By specifying a subrange, you indicate that the values of the variabJe Day-Of-Year are restricted to the integers from 1 to 366. Example TYPE Months = CJan, Feb, Mar, Apr, Mas~ Jun, Jul, Au~, Sep, Oct, Nov, Dec), VAR Camp_Mos: Mas •• Oct; Leaf_Mos: Sept.Nov; First_Half: 'A' •• 'M'; We> l"'cf: () •• t.l::.'.i5::~~;' This example defines the variables Camp_Mos and Leaf_Mos as subranges of the enumerated type Months. A Camp Mos value can be only May, Jun, Jul, Aug, Sep, or Oct. A Leaf Mos val~e can be only Sep, Oct, or Nov. The variable First Half is subrange of the ASCII characters, with possible values uppercase A through uppercase M. The variable Word is a subrange of the integers from a to 05535. a 2.2.2.3 The ORD Function - Each element of a scalar type (except the REAL type) has a unique ordinal value, which indicates its order in a list of elements of its type. The ORD function returns the ordinal value as an integer, for example: OR[lC '(~') This expression returns 81, which is the ordinal value of uppercase Q in the ASCII character set (see Appendix B). Note that the order of the ASCII character set may not be what you expect. The numeric characters are in numeric order, and the alphabetic characters are in alphabetic order. All uppercase characters have lower ordina] values than all lowercase characters, for example: ORDC'Q') OF~D( 'A') ORDC'Z') is less than ORDC'a') and is less than ORDC '7') but is less than ORD('a') You can use ORD on a value of an enumerated are ordered starting at zero, for example: type. Enumerated types Of,[I CTuef.)da~) Assuming that Tuesday is a value of type Weekdays values Monday, Tuesday, Wednesday, Thursday, expression returns the integer 1. the (which includes this and Friday), The ordinal value of an integer is the integer itself. For examp]e, ORD(O) equals 0, ORD(23) equals 23, and ORD(-1984) equals -1984. 2-7 PASCAL DATA TYPES 2.3 STRUCTURED DATA TYPES A structured data type consists of a collection of related data components; it is characterized by its method of structuring and its components. All structured data types consist of a collection of elements or components that are grouped together in a structure in which they can collectively be manipulated. PASCAL provides four structured data types: • ARRAY • RECORD • SET • FILE An array is a group of components of a predefined size and of the same type. A record consists of one or more named fields, each of which contains one or more data items. Records can include fields of different data types. A set is a collection of data items of the same scalar type, the base type. You can access a set as an entity, but you cannot access the set components as individual components or variables. A file is a sequence of data components that are of the same type; each component can be individually accessed. A file can be of variable length. Section 2.3.1 describes arrays; Section 2.3.2 describes records; Section 2.3.3 describes sets; and Section 2.1.4 describes files. 2.3.1 Array Types An array is a group of components of the same type that share a common name. You refer to each component of the array by the array name and an index (or subscript). An array type definition specifies the type of the indices and the type of the components. Format ARRAY [index type [,index type ••• ] ] OF component type where: index type specifies the type of the index. The (ndex type can be a subrange, CHAR, BOOLEAN, or enumerated type; but it cannot be a REAL type. component type specifies the type of the components array. of the The components of an array can be of any type. For example, you can define an array of integers, an array of records, or an array of real numbers. You can also define an array of arrays, which is known as a multidimensional array. The indices of an array must be of a scalar type, but cannot be real numbers. Note that you cannot specify the type INTEGER as the index type. To use integer values as indices, you must specify an integer subrange, unless you are using conformant-array parameters. If necessary, PASCAL determines the subrange. For example, if the index 2-8 PASCAL DATA TYPES is BOOLEAN, then PASCAL converts the subrange to FALSE •. TRUE because the type BOOLEAN has only two legal values. For more information about conformant-array parameters, refer to Section G.3.2. The range of the index type establishes the size of the array and way it is indexed, for example: TYPE Letters VAR Letl: ~ ARRAY [1~.10] OF the CHAR~ Letters~ The array variable LETl has 10 components, referred LETl r2], LET 1 [31, and so on, through LETI no]. to as LETlrl], You can use array components in expressions anywhere you can use variables of the component type. For the array as a whole, however, you can use only the assignment statement (:=). An exception to this rule is made for character strings, which PASCAL defines as packed arrays of type CHAR. See Section 2.3.1.2. 2.3.1.1 Multidimensional Arrays - An array with components of an array type is a multidimensional array. An array can have any number of dimensions, and each dimension can have a different index type. For example, the following declares a two-dimensional array variable: VAR Two_D: ARRAY [0 •• 4J OF ARRAY ['A' •• 'D'] OF INTEGER; PASCAL allows you to abbreviate the definition by specifying index types in one pair of brackets, for example: all the ARRAY [O •• 4,'A' •• 'D'] OF INTEGER; To refer to a component of this array, you specify two indices, one integer and one character, in the order they were declared: Two_D[O,'A'l, Two DrO,'B'], and so on. You can a]so specify Two D[O]r'A']. The first index indicates the rows of the array, and the-second index indicates the columns. Hence, you can picture the array Two D as in Figure 2-1. 'A' '8' 'C' '0' o 2 3 4 MR-S-3113-83 Figure 2-1: Two-Dimensional Array Two D 2-9 P~SCAL DATA TYPES When referring to the components of Two D, the first component in the first row is Two Dro,'.a.'l. The second component in this row is Two D ro,' B' 1. The Ii rst component in the second row is Two D rl,' A'] • The- last component in the last row is Two Dr4,'D']. general, element j of row i is Two_Dri,jl. - In You can define arrays fashion, for example: VAF< Ch (.;.~ s s :3 II of three : . f.l f< F< AY [1..;3 ~ or more :I... n, dimensions in a similar nr::. •1\ F< ::I 0 F C h (.:.~ ~:; ~:; 1'1'1 e 1"1 ; This declaration specifies a three-dimensional chess game. The indices of the array are the levels, the ranks, and the files of the chessboard. For example, the reference Chess3D fI, 1, QR] specifies the first level, first square in the upper left corner (bottom lev~l, first rank, Queen's Rook file). Figure 2-2 illustrates the three levels of this array. Chess3D(1,n, Chessmen) (bottom) Chess3D(2,n, Chessmen) (middle) 1 OR ON OS 0 K KS KN KR Chess3D(3,n, Chessmen) ( top) Cf-IESS3D{3.n. CHESSMEN/ CHESS3D{2.n.CHESSMEN/ CHESS3D{I.n.CHESSMENj lK 098 81 Figure 2-2: Three-Dimensional Array Chess3D When storing values in an array, PASCAL increments the indices from right to left. Thus, PASCAL increments the rightmost index until the maximum value is reached, then moves to the left to the next index, and so on, until all indices have been incremented to the specified amoun t. 2-10 PASCAL DATA TYPES In the three-dimensional array Chess3D, PASCAL starts by holding the first two indices constant while stepping through the values of Chessmen. Thus, the first values are assigned to components Chess3D fl,I,QR] through Chess3D fl, 1 ,KR] • Next, the second index is incremented and values are assigned to the components Chess3D [1,2,QRl through Chess3D[1,2,KR1. After these eight elements are assigned, the second index is again incremented, and values are assigned to Chess3D rl,3,QR] through Chess3D rl,3,KR]. The assignment process continues with the first index held constant until the second index has been incremented from 1 to 8. Then, the first index is incremented, and the process is repeated. Hence, all values for the bottom level (denoted by Chess3D[1,n,Chessmenl) are stored before any values for the middle level (denoted by Chess3D [2,n,Chessmen]). The top level (denoted by Chess3Dr3,n,Chessmen]) receives its values last. Figure 2-3 illustrates this order. OR ON as - a K ~:-:~;:: ::::=::=-+f----+----+--..--1--_--1 ~ . __ j 4 .....-,1--t--+-+-+--+-.-+---1 : - - --".5 -- -or' ""'-'--+-+--f---t-- - [:: -.> 6 ~I--t-+-+--+--+--+----l (: ~)7 I--+--+--+--f---t--- _ . :_-. ~ -~> 8 OR ON os KS KN KR 1 .....-,I--t--+- I---+--+--+---i '---'---'---L- 0 K OR ON KB KN KR os a K KS KN KR ~12 f------1--t--+-+--+-+--+--1 • - - . A. ~. -.-J : _:.'3 -f-- , >4 . - ----. f--- , " .'. f--f----jl--t--+-+--+-+-t ~ ~ ~ :.) 5 f----t-+-+-t---+-+--+-t ~ :-.:. ' 6 .....-,I--t-+-+--+--- f---- :-> ~ -;" 7 f------I--t--+-+-+- +-_ +---u. '-----J'----'-----L---'_--'---'---'--~II CHESS3D (I ,n,CHESSM[N ( lbo)ttom) CHESS3D (2.n,CHESSMEN ( CHESS3D (3,n,CHESSMEN] (middle) Itop) MR-S-3115-83 Figure 2-3: Storing Components in an Array 2.3.1.2 String Variables - A character string variable in PASCAL is defined as a packed array of characters with a lower bound of 1. To declare a string variable, specify a packed array of the proper length, for example: VAR NAME PACKED Af;:RAY [1 + + 20] OF CHAR; : This declaration allows you to store a string of 20 characters in the array variable NAME. The length of this string must be exactly 20 characters. PASCAL neither adds blanks to extend a shorter string nor truncates a longer string. You can assign to a string variable the value of any string constant or variable of the defined length. You can also compare strings of the same length with the relational operators <, <=, >, >=, =, and <>. The result of a string comparison depends on the ordinal value (in the ASCII character set) of the corresponding characters in the strings, for example: 'motherhood' > 'apple pies' This relational expression is TRUE because lowercase 'm' comes after lowercase 'a' in the ASCII character set. If the first characters in the strings are the same, PASCAL looks for differing characters, as in the following: Istrin~l' < 'strin~2' This expression is also TRUE because the digit I in the ASCII character set. 2-11 precedes the digit 2 PASCAL DATA TYPES To assign a string constant to an array in the executable section, use an assignment statement. The string variable must be of the same size as the array; otherwise, an error occurs. The following example shows an assignment statement in the executable section: TYPE Strin~ ~ VAR Word Strin~; PACKED ARRAY[1 •• 10J OF CHAR; BEGIN W0 l' (.j : ~~ .' () T' a n ~.:.~ e I' Y END; The string constant 'orange' of the array. is padded with spaces to match the size The READ and READLN statements automatically pad the string constant if necessary. Thus, it is not necessary to pad the string constant with spaces to match the varjable size, when using the predefined file INPUT or reading from a file defined as TEXT. 2.3.1.3 Initializing and Assigning Values to Arrays - You should assign values to an array either in the declarations or the executable section before using the array within the program. As with all variables, the value for each component is undetermined, until a value is specifically assigned. To assign values to an array in the executable section, a value must be assigned to each component in the array. One method of doing this is to use a FOR statement. By using the FOR statement control variable as the array index, it is possible to step through all components of the array, setting them to the same initial value. Each index for the array is incremented at the same time the counter in the FOR statement is incremented. An example of this is: VAR Arrau_ExaffiPle : ARRAY [1 •• 10J OF INTEGER; I ncip>: : INTEGER; BEGIN FOR Index := 1 TO 10 DO A T' r a ~~ .... E ~.: a IT! P 1 €.~ [I n (j (., ~-: :1 : :::: 0; END, In this example, the array has been defined as being an array of type INTEGER. As the FOR loop executes each time, the counter is incremented by one. Likewise, the index is incremented by one. On each execution of the loop, the current component is assigned a value of o. An array can be initialized in the VAR section. The following example shows each component of the array Array_Example being initialized with the value 0: ARRAY [1 •• 10] OF INTEGER 2-12 := (10 of 0); PASCAL DATA TYPES To assign values to a two-dimensional array in the executable section, you can use two nested FOR statements to increment the two indices, as shown in the following example: Zf.~ ro :::: <>; VAR Table: ARRAY [1 •• 10,1 •• 5J OF INTEGER; i n (.l f:·~ >~ .... 1 , i :1".' (i (.:~ >( .... 2 : I NT E GE R ; CON~:>T BEGIN F (] F~ i n d f:~ ~.( .... 1 : :::: FOR index_2 :I. T () :l ° DO := :l TO 5 DO Table[index_:l,index_2] := Zero; END~ Array_Example is INTEGER. :lefined to be a two-dimensional array of type The nested FOR statements assign the value of Zero (which has been assigned the value of "0" in the CaNST section) to each component in the array. To initialize a two-dimensional array in the VAR section, specify a constructor for each row, in parentheses. The following example shows a two-dimensional array that is initialized in the VAR section: VAR Table ARRAY [1 •• 10,1 •• 5] OF INTEGER := (10 OF (5 OF 0»; To assign values to arrays of three or more dimensions executable section, use three or more nested FOR statements: in the 0, CONST Zero:::: VAR Table: ARRAY [1 •• 5,1 •• 3,1 •• 2J OF INTEGER, index_l"index_2,index_3 : INTEGER; BEGIN FOR index_1 := 1 TO 5 DO FOR index_2 := 1 TO 3 DO FOR index_3 := 1 TO 2 DO TableCindex_l,index_2] := Zero; END; This example shows the initialization of a three-dimensional array. The value of· Zero is assigned to each element in Table, from Table[l,l,l] to Table(5,3,2]. To initialize an array of three or more dimensions in the VAR section, specify a constructor for each row. The following example shows a three-dimensional array being initialized in the VAR section~ VAR Table: ARRAY [1 •• 5,1 •• 3,1 •• 2] OF INTEGER := (5 OF (3 OF (2 OF ' 2-13 '»); PASCAL DATA TYPES 2.3.1~4 Array Type Compatibility - You can assign one array to another only if the arrays are either identical or compatible. Arrays of the same type or equivalent types are identical. The following example demonstrates identical arrays: TYPE VAR Salar~ ~ ARRAY [1 •• 50J Pay = Salary; WaSe~ Income or REAL; Money : Pay; The arrays Wage and Income are identical because both are of type SALARY. The array ~oney of type PAY is identical to Wage and Income because the type PAY is declared equivalent to the type SALARY. Identical arrays are always compatible. Arrays that Are not identical following criteria: are compatible if they meet all • They have the same number of components. • Their elements are of compAtible types. • Their indices are of compatible types. • The upper bounds of their indices are equal. • The lower bounds of their indices are equal. • Both are packed or neither is packed. • For packed arrays of subrange types, the subranges must be the same for both types. The following two array types, bounds of the of the though not identical, are compatible: TYPE Grades = ARRAY [1 •• 28] OF 0 •• 4; Feb_Temps = ARRAY [1 •• 28J OF INTEGER; Both types define arrays with 28 components, indexed from 1 to 28. The integer subrange components of type GRADES are compatible with the integer elements of type Feb Temps. Therefore, you can assign variables of type GRADES to -variables of type Feb Temps, and vice versa. Note that, if the TYPE definition specified packed arrays, the types GRADES and Feb_Temps would not be compatible. PASCAL does not check for valid assignments to subranges that are part of a structured type. If you assign an array of type Feb Temps to one of type GRADES, you must ensure that the values are in -the correct range. An out-of-range assignment does not result in an error message, even if the CHECK option is enabled at compile time. 2-14 PASCAL DATA TYPES 2.3.1.5 Array Examples - Example 1 TYPE Times = 1 •• 10; VAR Raceresults : ARRAY[1 •• 50J OF Times; I : I NTEGEfn BEGIN := 1 TO 50 DO Raceresults[IJ != 0 FOR I END; This example decl~res the variable Raceresults as a 50-component array of Times. The FOR statement assigns zero to each component in the array. Example 2 T YP E f:) t, r i n 9 ,,: PAC KED AF~ RAY [1.. 1 () ] 0 F CH AFU VAR Composer, Word, Empt~ : String; BEGIN Word := 'engrossing'; Composer := 'C.P.E.Bach'; EITJPt~:J ::::: I END; This example declares three string variables. It assigns string constants to the variables Word and Composer, and assigns a string of 10 spaces to the variable Empty. Example 3 CONST Da\.~~:; :::: 31; TYPE Weather:::: (Rain, Snow, Sunn~, Cloud~, Month = ARRAY C1 •• DAYS] OF Weather; Fogg~); This example shows how you can use a constant identifier in the index type. The indices of arrays of type Month range from 1 to the value of the constant Days. 2.3.2 Record Types The record is a convenient way to organize several related data items of different types. A record consists of one or more fields, each of which contains one or more data items. Unlike the components of an array, the fields of a record can be of different types. The record type definition specifies the name and type of each field. 2-15 PASCAL DATA TYPES Fo rma t RECORD field id : type [;field id variant clause } type ... ] [variant clause] END; where: field id specifies the names of one or more fields. The names must be identibfiers and must be separated by commas. type correspond ing specifies the type of the field(s). A field can be :=Iny type. variant clause variant of the specifies the part fo r the record. See Section 2.3.7..1 fo rma t of a variant c]ause. The names of the fields must be unique within the record, but can be repeated in different record types. For instance, you could define the field NAME only once within a particular record type. Other record types, however, could also have fields called NAME. The values for the fields are stored in the order in which the are defined, for example: VAf~ fields TealYl ... HE'C ! F,[COHD I,J:i.n'5: INTEGEH; Losses : INTEGER; Pe T'cent : F<EAL END; The values for these fields are stored Percent. in the order Wins, Losses, To refer to a field within a record, specify the name of the rec~rd variable and the name of the field, separated by a period. For example, Team Rec.Wins, Team Rec.Losses, and Team Rec.Percent refer to the three fTelds of the -record Team Rec decTared above. You can specify a field anywhere in the program that a variable of the field type is allowed. Thus, you could write: Records can include fields that are themselves records, VAR Order : RECORD Part : INTEGER; Received : RECORD Month for example: (Jan, Fe~, Mar, Apr, Ma~, Jun, Jul, Au~, Sep, Oct, Nov, Dec); : 1 •• 31; Year : INTEGER END; Inventory : INTEGER END; Da~ 2-16 PASCAL DATA TYPES The fields in this record are referred to as Order.Part, Order.Received.Month, Order.Received.Day, Order.Received.Year, and Order. Inventory. The WITH statement provides an abbreviated notation for specifying the fields of a record (see Section 5.5). 2.3.2.1 Records with Variants - To allow a record to contain different data types at different times, you can define a record variant. To do this, specify one or more variants in the TYPE definition. A variant is a field or group of fields that can contain a different type or amount of data at different times during execution. Thus, two variables of the same record type can contain different types of data. To specify a variant, include a variant clause in the record type definition. The variant clause must be the last field in the record. Fo rma t CASE tag fieJd OF case-label list ( [field id type] type ..• ] ); [;field id where: tag field indicates the current variant of the record. You can specify the tag field in two ways: I . tag name : tag type If you use this form, the tag field is a field in the record that is common to all variants. Tag name and tag type define the name and type of this field. The tag type can be any scalar type except a REAL type. You can use the tag field in the same way that you use any other field in the record; that is, you can use the record.fieldname fo rma t. 2. tag tYPE~ If you use this form, you must keep track of the currently valid variant. The tag type can be any scalar type except a REAL type. case-label list specifies one or more constants field type. field id specifies the names of one or more fields. The field names must be identifiers and must be separated by commas. Note that, instead of the field identifiers, you can specify another variant clause, as in the last example in this section. type ~pecifies of the the type of the variant field. type cannot be a FILE type. 2-17 tag The PASCAL DATA TYPES When you specify the tag field in the first form (tag name tag type), you should reference on] y the fields in the currently val i(] variant. The following example shows the use of this form: TYPE Name ~ PACKED ARRAY [1 •• 20J OF CHAR, D a '.:~ ;;;: (M 0 n ~ T 1..1 (~~ y Wp (j ~ T h IJ, F l' i ) ; ~~ t () C k ::" F< E C Cl F< 1:1 F'd r t : 1.. (;9 (J 9 , Stoc~_Quantit~ : INTEGER, f:>upp J if:" r : Name; CASE Onorde1' : BOOLEAN OF T"HUE :(P1'omi~:;pd: Da~:I; I NTEGEF<; o T' d f.~ T' _. (J u ant i t ~~ Price: REAL); Da~:~ ; FALf:;C : (l..ast .... :~hipmf.·~nt INTEGER, F<pc .. _Ouant:i. t~~ Co~:;t : F<EAI. . ) END, Tn this example, the last three fields in the record type vary depending on whether the part is on order. The tag name Onorder is defined in the variant clause. Records for which the value of Onorder is TRUE will contain information about the current order. Records for whi~h this variable is FALSE will contain information about the previous shipment. In the second way of specifying the tag field, type, as in this example: TYPE = = Name PACKED ARRAY [1 •• 20J Date ::" I NTEGEf<; Sex (Female, Male), HOSF' ;:~ you use only a tag OF CHAR; RECOF<D Pat i f:~nt : Nam~l; Birthdatp : Date; A~H? : CASE I NTEGEI=i:; Se~< OF 1 •• 30) ; Fe ITI ale : ( B i r t h s Male: () END, Tn this example, you must keep track of the currently valid variant. You can define a variant onJy for the Jast field in the record. Variant fields can, however, be nested, as in the following example: TYPE Name = PACKED ARRAY [1 •• 20] OF CHAR, Date =" INTEGER; Sex = (Female, Male); HosF' = RECORD Patient : Name; Bi1'thdate Age : : Date; INTEGER; CASE Pa1'sex : Sex OF Male : Female ( ) ,(CASE Births : BOOLEAN OF FALSE: (); TRUE : (Nok i ds : INTEGER» END; This record type contains the name, birthdate, age, and sex of all patients. In addition, it includes a variant field for each woman based on whether she has had any children. A second variant, which contains the number of children, is defined for women who have given birth. 2-18 PASCAL DATA TYPES 2.3.2.2 Assigning Values to Records - To assign values to a record variable, use an assignment statement to specify a value for each field of the record. The following example shows the declaration of a record and the assignment of values to two of the fields. TYPE ROSTER - RECORD Name: PACKED ARRAY[1 •• 30J OF CHAR; Number: INTEGER; Grade:: I:::EAL..; END; VAR Student ROSTER; Testl,Test2,Test3 INTEGER; BEGIN WRITEL..N ('Enter your name.'); READLN (Student.Name); Stu(·.lf~'nt • GJ'i:H:.h:~ : =:: (T es t 1 + TE~S t2 + T€.'S t3) / :3; If you are initializing a record with a variant clause, you must always specify a value for the tag field, even if it has no tag name. Specifying a value for the tag field, ensures that PASCAL initializes the correct variant, for example: TYPE Sex = (Male, Female); Pe rson ::;; RECORD Birthdate: RECORD Month: 1 •• 12; Day: 1 •• 31 ; Year: INTEGER; END; Ase: INTEGER; CASE s~~~< of (Bearded:BOOLEAN); Male: Female: (N_Children:INTEGER); END; VAR Dad: Person := «5, 15, 1921), 62, Male, TRUE); 2.3.2.3 Record Type Compatibility - Two records are their types are identical or equivalent, for example: TYPE Life compatible if = RECORD INTEGER; :Born INTEGER :Died lEND; Plantlife = Life; VAR Mom, Dad : Life; Coleus : Plantlife; The record variables Mom, Dad, and Coleus are all compatible. Mom and Dad are both of type Life, which is equivalent to type Plantlife. 2-19 PASCAL DATA TYPES Records of differing types are compatible if they meet criteria: • They have the same number of fields. • Corresponrling field types are compatible. • Both are packed, or neither is packed, corresponding fields equal bounds. packed. If of subrange the following the types are types must have The following type is also compatible with Life and Plantlife: TYPE Coords = RECORD X : Y : INTEGER, O •• lOO END; The integer subrange O.. 100 is compatible with the type INTEGER. However, PASCAL does not check for valid assignments to fields of subrange types. If you assign a record of type Life to a record of type Coord, you must ensure that the value of the field Died is within the subrange O .• 100. An out-of-range assignment does not result in an error message. If the records have variants, these criteria also apply: • The records must have the same number of variants. • Corresponding variants must have the same number of fields. • Corresponding field types within corresponding variants be compa t i bl e. • The case labels associated with the variants number, but need not agree in value. • Corresponding variants in structurally must have identical tag constant values. • The tag constant lists in each record must be identical. 2-20 must compatible agree must in records PASCAL DATA TYPES For example, definition: assume the program includes 'A/ •• /D/;: I<[CORD Siz(? : INTEGER; Calories : INTEGER; ProtE~in :: 0 •• 40; ea rb : I NTEGEFU CASE Vi ts : Lf:~ts OF 'A'!"C','D': ( ) ; 'B' : (Niacin, Thiamine END, 'A' •• 'F', GT'adps F,[CORD School Studentno : INTEGER, Clas~:;: 1 •• 5; the following TYPE TYPE I... (::~t~:; Info HCH.IT'S : BOOLEAN) 1 •• ~~O; Incompletes : 1 •• 6; CASE Average : Grades OF 'B','C','D' : ( ); 'A' : (Sendlet, Firstsem END; BOOL.EAN) The types Info and School are compatible. If you assign a variable of one type to the other, however, you must be sure that both contain the same variant. 2.3.2.4 Record Examples - Example 1 TYPE Taxes - RECORD Year : INTEGER; Gross : REAL; Net : REAL; Deductions : INTEGER; Itemized BOOLEAN; Interest ARRAY [1 •• 5] OF REAL END; VAR Fed Taxes := (1981, 25234.12, 18789.00, 4, TRUE, (5 of 0.05»; This example declares and initializes the record Fed of type Taxes. 2-21 PASCAL DATA TYPES Example 2 T Y PES t l' i n ~.l :::; F' (.1 C1\ E It A F~ F< A Y [: 1. • • 2 () ::I Personal nF CH A F~ ; F~[COF<D N a ITt e ~:; t T' i n ~.:.l ; : Add T'e~;~:; : ~-::ECnF<D Numbe1' : INTEGER, Town : Zip: 0 •• <;<;<;99 ~:)t1'€~pt, !:;trin~:j; END, A~lP : () •• :t '.:.:jO END; VAH Facl..ll t~~, F'P r~:;ona 1 ; Mascot, Stuclent BEGIN , := 'Niklaus Wirth Facult~.Address.NulTtber := 5; Facl..llty.Address.Strpot := 'Clausiusstrdsse , Facl..llt~tNalTte A , , A END, The type Personal contains the field Address, which is of a record type. To assign values to each of the fields of the record Address, you must also specify the record Faculty in the assignment statement. 2.3.3 Set Types A set is a collection of data items of the same scalar type, which is known as the base type of the set. Unlike arrays and records, elements in the set cannot be accessed individually. In PASCAL, you use a set as an individual unit. The type definition specifies the values for each element in the set: Fo rma t TYPE identifier SET OF base type where: identifier specifies the type identifier for the set. base type specifies the data type. Each element in the set must be of this data type. You can use the identifier or definition of any scalar type except a real TYPE. A set can have up to 256 members, and the value of each member must be between 0 and 255. Therefore, real numbers or integers outside the range 0 to 255 cannot be set elements. After defining a base type, you can type, for example: declare set variables of SET OF (Racauet, Shoes, Balls, Boots, Skis, F'oles, Goggles, Swimsuit); 2-22 that PASCAL DATA TYPES Sets are compatible if their base types are identical for example: or equivalent, TYPE Vitamins = SET OF (A, B1, B2, B6, B12, C, D, E, K), Nutrients = Vitamins; VAR Watersoluble, Fatsoluble Def:i. c i (o:o)folt : Nut J' i f.o)nts; Vitamins, The VAR section specifies three mutually compatible sets. compatible base types are also compatible, for example: VAR Sets wi th Specials is ASCII : SET OF CHAR; S pee i a 1. ~:; : SET (] F I! 1 • + 1 / I; These two sets ~re compatible because the base compatible with the ASCII character set. type of Packing has no effect on set compatibility except when passing sets as VAR parameters. An unpacked set is compatible with a packed set if both sets meet the criteria above. You can build set expressions by using the set operators described in Chapter 3. Set operators allow you to specify set intersection, difference, union, inclusion, and containment. In addition, you can assign a set expression to a set variable. The base type of the variable must include all members of the set to which the expression eval ua tes. Example 1 TYPE Caps = SET OF CHAR, VAR Vowel: Caps:= ConsDnant : Caps [/A/,/E/,/I/,/O/,/U']; := £: 'B' + + '[I', 'F' + + 'H',' J'. + 'N', 'P' •• 'T','V' •• 'Z']; These declarations specify the set type Caps and two set variables, Vowel and Consonant. The set Vowel is initialized with the set of vowel characters as initial values. The set Consonant is initialized with the set of consonants. Example 2 VAR Ages This example declares and initializes a set with an integer base type. 2-23 PASCAL 2.3.4 D~TA TYPES File Types A file is a sequence of data components of the same type. The number of components in a file is not fixed; a file can be of any length. The file type definition specifies the type of the file components. Fo rma t TYPE identifier FILE OF component type where: component type specifies the type of the components of the file. The component type can be any scalar or structured type except a file type or an array or record type containing a file element or field. The arithmetic, relational, Boolean, and assignment operators do not work on file variables or structures containing file components. For example, you cannot assign one file variable to another file variable, nor can you initialize a file variable. Type compatibility for files applies only to file parameters. Two file parameters are compatible if their components are compatible and if both are packed or neither is packed. You can pass a file only as a VAR parameter. PASCAL automatically creates a buffer variable for each file variable you declare. The type of the buffer variable is the same as the type of the file components. To denote the buffer variable, specify the name of the associated file variable fo] lowed by a circumflex (~), for example: TYPE Scores = FILE OF INTEGER; Scores; VAR Math_Scores: PASCAL creates ~ath Scores~ as an integer buffer variable associated with the file Math Scores. The buffer variable takes on the value of the file at the cur~ent file position. The predeclared input and output procedures move the file position, thus changing the value of the buffer variable. Example I VAF, T ruthva 1. s FIL.E OF' BOOLEAN; This declaration specifies a file of Boolean values. variable for this file is denoted by Truthva]s~. The buffer Example 2 TYPE Names = PACKED ARRAY [1 •• 20] OF CHAR; or Data .... Fi Ie :::: FILE Names; RejecL.List, Wait_List: VAH Accept .... L..ist" Data_File; This example defines the array type Names and the file type DataFile, which contains a list of names. The VAR section specifies three file variables of type DataFile, with associated buffer variables Accept_List~, Reject_List~, and Wait List~. 2-24 PASCAL DATA TYPES Example 3 F I 1...[ OF RECOf~D TY'ial INTEGER; Datf:'~ RECOF~D Month: (Jan, Feb, Mar, Apr, Mas, Jun, Jul, Aug, Sep, Oct, Nov, Dec); Da ~:1 Y€·~ar : 1.. 3 l ~ : INTEGER END; Temp, Pressure : INTEGER; Yield, Purits : REAl... END; The VAR Declaration specifies a file of records. To access the fields of the record components, you specify ResultsA.Trial, ResultsA.Date.Month, and so on. 2.3.4.1 Internal and External Files - A file that is local to a program or subprogram is called an internal file. You can use an internal file only within the scope of the program or subprogram in which it is declared. The system retains an internal file only during execution of the declaring program or subprogram. After execution the file is no longer accessible. The system creates a new file variable with the same name the next time it executes the declaring unit. The contents of the old file are not available. Internal files are not specified in the program heading. Only internal files can be components of structured types. An external file exists outside the scope of the program in which it is declared. An external file can be created by the current PASCAL program, another PASCAL program, or a program written in another language. The system retains the contents of external file variables after the execution of the program. You must specify the names of external file variables in the program heading. External files cannot be part of a structured type. 2.3.4.2 Text Files - A text file is a file with components of type CHAR. PASCAL defines a file type called TEXT. To declare a text file, specify a variable of type TEXT, for example: VAR Poem TEXT; The text file variable POEM is a file of characters. Text files are divided into lines. Each line ends with a line-separator character. You cannot use this character directly, but you can refer to it indirectly through the predeclared procedures READLN and WRITELN and the predeclared function EOLN. The pred~clared file variables INPUT and OUTPUT are files of type TEXT. These files are the defaults for all the predeclared text file procedures described in Chapter 7. Note that TEXT is not equivalent to FILE OF CHAR. Example VAR Guide, Manual: TEXT; This example declares the Variables Guide and Manual as text files. 2-25 PASCAL DATA TYPES 2.4 POINTER TYPES Normally, variables have the same lifetime as the program or subprogram in which they are declared. Program-level vari~bles are allocated in static storage, and subprogram-level variables are allocated on the stack. Some applications, however, require different lifetimes or an unknown number of variables of a certain type. PASCAL allows you to use dynamic variables to fill these requirements. Dynamic variables are dynamically allocated as needed during program execution. Unlike other variables, dynamic variables are not named by identifiers. Insie~d, you must refer to them indirectJy with pointers. A pointer type thus allows you to declare any number of pointer variables to refer to dynamic variables of a specified type. Each pointer variable assumes as its value the ~ddress of a dynamic variable. The pointer type definition specifies the type of the dynamic variable to which pointers of the pointer type refer. Fo rma t TYPE identifier Abase-type identifier where: base-type identifier indicates the type of the dynamic variable to which the pointer type refers. The base type can be any type. Note the following example: TYPE MYrec = RECORD A ~ B d:: ENIH Ptr_To_Myrec VAR M : : INTEGER = ~MYrec~ Pt T' _.. T D .... M!:j Y'PC Y Variables of a pointer type point to variables of the base type, and are said to be bound to that type. To indicate a pointer variable, specify its name. To indicate the dynamic variable to which a pointer is bound, specify the pointer name followed by a circumflex(A). For example, M is a pointer variable bound to records of type Myrec. Specify MA to denote the record variable to which M points. 2-20 PASCAL DATA TYPES Pointer type definitions are the only place in a PASCAL program where you can use an identifier before you define it. PASCAL allows you to use the base type identifier in a pointer type definition before you define the base type, for example: TYPE Ptr_To_Movie ~ ~Movie; Nam(,~ :::: F',:':JCKED ARri:AY [:t •• 20:3 OF CHAFi:; Mov :i. (.:~ :::: Fi:FCOI:;:D Title, Director : Name; Yf:'~ a Y' : I NT E C! E I~: , Stars : FILE OF Name; Next : ptr_To_Movie END; The TYPE section specifies the type identifier Movie the type Movie. before defining The value of a pointer is the storage address of the variable to which it points. Thus, in the example above, the value of the field Next is a pointer to (or address of) a dynamic record variable of type Movie. Pointers assume values at initialization, by assignment, and through the NEW procedure. The value of a pointer can be any legal storage address. The value NIL indicates that the pointer does not currently specify an address. Thus, a NIL pointer does not point to a variable. PASCAL allows you to define pointers to types example: TYPE containing files, for x:::: "'Y; Y::~ RECORD P : I NTEGEf;:; Q : ARRAY[:ttt3] OF TEXT END; VAR M:X; The pointer type X points to record type Y, which contains a file component in field Q. The files denoted by Q are never closed until execution of the program terminates, unless you use the CLOSE procedure. For example, to close the files defined in the TYPE section above, you must call CLOSE with the parameters MA.Q[l], A M .Q(2], M".Q[31. You can assign the constant NIL to a pointer as follows: As a result of the assignment, the pointer variable M does not point to a variable. NIL is the only value you can specify to initialize a pointer. 2-27 PASCAL DATA TYPES Example :;;: {~ F< ~-;; A Y [1.. 30 ::I 0 F C H A F< ~ f' t r' ... T (J .... H :i. t ~:; :::: ,', Hit ~; , H i. t <:; ::: F~ [ C n P I:I T Y PEN d IT! f.~ Title, Artistv Composer: Name; I NT [ GER ~ We p k. ~:; .... n n .... C h art y N.... ~:) 0 :I. (J : F :i. T' ~:; t .... V p r ~:; :i. 0 n : B 0 [) I... E (I N END, VA f< To F·' t f..1 n I : : A R F.: A Y [1.. 1 () J 0 F F' t J" .... To .... Hit ':; , INTEGEF<; BEGIN F (] I:~ :r : ::: 1. TO :I. 0 II 0 ToptenlIJ := NII...~ END, This example defines the record type Hits to which pointers of type Ptr To Hits refer. The array variable Topten has elements of the pointer type Ptr To Hits. E~ch element of the array is assigned the constant value NIL. The array Topten could be used in creating a Jist of ten records of type Hits. 2.5 PACKED STRUCTURED TYPES You can pack any of the structured types by specifying PACKED in the type or variable declaration. Packed data items are stored as densely as possible. Fo rma t PACKED type definition where: type definition defines an array, record, set, or file type. You can initialize all packed structures in the VALUE or VAR section in the same way that you initialize an unpacked structure of the same type. In general, packed data items require less storage space than unpacked data items of the same type. However, execution is usually slower with packed data items. In PASCAL, a packed array of characters specifies a string variable. Example 1 TYPE I:<an~:jes .::: PACI\ED RECORD Wo rei : 0 •• 6:::j~)3:::j; B~t(~ : O •• 32/(,)/; Bit : BOOLEAN END; This example defines a record type with three fields, each of which is packed as densely as possible. 2-28 PASCAL DATA TYPES Example 2 VAR : PACKED ARRAY [1 •• 25J OF 2500 •• 50000; I NTEGEF: i; Cit~_Census J : BEGIN FOI:< I: : :~: :L TO 2~:.:j DO C 1. t ~~ .... C(.:~ n sus I:: I] ! :=: (); END; This example declares the variable City Census as a 25-element array of integer values in the subrange from ~500 through 50000. A value of a is assigned to each element of the array. 2.6 TYPE COMPATIBILITY Type compatibility rules determine the operations and assignments that you can perform with data items of different types. Two scalar types are compatible if their type identifiers are declared equivalent in the TYPE section. In addition, a subrange type is compatible with its base type, and two subranges of the same base type (or equivalent base types) are compatible. For structured and pointer types, PASCAL enforces structural compatibility. Two structured (that is, arrays, records, files, and sets) or pointer types are compatible if their structures are identical. The way PASCAL determines structural compatibility depends on the record types involved. For instance, the requirements for compatibility differ from those for array compatibility. PASCAL uses compatibility rules in the fo]lowing three contexts: 1. Expression compatibility 2. Assignment compatibility 3. Formal and actual parameter compatibility Expression compatibility determines the types of operands you can in an expression. See Chapter 3 for information on expressions. use Assignment compatibility determines the types of values you can assign to variables of each type. Assignment compatibility rules apply to value initializations, assignment statements, and value parameters. Assignment compatibility is described with the assignment statement in Section 5.2. Formal and actual parameter compatibility determines the types of data you can pass in a parameter list. Value parameters follow the rules for assignment compatibility. Variable parameters follow somewhat different rules. Value and variable parameters are described in Chapter 6. 2-29 CHAPTER 3 EXPRESSIONS An expression is a symbol or group of symbols that PASCAL can evaluate. These symbols can be constants, variables, or functions, or any combination of constants, variables, and functions, combined with operators. The simplest expression is a single variable or constant. This chapter lists the various operators that PASCAL provides along with the rules for forming arithmetic, relational, logical, and set expressions. 3.1 OPERATORS PASCAL provides the following types of operators: 3.1.1 • Arithmetic operators (such as +, - /) • Relational operators (such as <, >, =) • Logical operators (such as AND, OR, NOT) • Set operators (such as IN) ArithmetIc Expressions An arithmetic expression usually provides a formula for calculating a value. To construct an arithmetic expression, you combine numeric constants, variables, and function identifiers with one or more of the operators from Table 3-1. 3-1 EXPRESSIONS Table 3-1: Operator Arithmetic Operators Example Meaning -------------------------- A+B Add l\ and B A-B Subtract B from A * A*B Multiply A by B ** A**B Ra ise A to the power of B I AlB Divide A by B DIV A DIV B Divide MOD A MOD B Produce the remainder after dividing A by B; B must be greater than 0 + A by B and truncate the result The addition, subtraction, muJtiplication, and exponentiation (+, , *, and **) operators work on both integer and real values. They produce real results when applied to real values and integer results when applied to integer values. If the expression contains values of both types, the result is a real number. The only exception to these rules concerns exponentiation. PASCAL defines the results of an integer raised to the power of a negative integer as follows: Base Result Exponen t 0 Negative or 0 1 Negative Error 1 -1 Negative and odd -1 -1 Negative and even 1 Negative o Any o the r integer For example, the expression 1**(-3) equals 1; (-1)**(-4) equals 1; and 3**(-3) equals o. (-1)**{-3) equals -1; The division (I) operator can be used on both real and integer values, but always produces a real result. Use of the division (I) operator can therefore cause errors in precision in expressions involving integers. The DIV, MOD, and REM operators apply to integer values only. DIV divides one integer by another, producing an integer result. DIV truncates the result; that is, it drops any fraction. It does not round the result. For example, the expression 23 DIV 12 equals 1, and (-5) DIV 3 equals -1. The MOD and REM operators return the remainder after dividing one operand by another. Both operators can be used only with integer values and always produce integer results. The MOD operator can be used only when the divisor is greater than 0; it always returns a positive result. For example, the expression 5 MOD 3 (5 modulo 3) returns a value of 2, and (-5) MOD 3 returns a value of 1. 3-2 EXPRESSIONS The REM operator can be used on integers of all sizes and retains the sign of the dividend. For example, the expression 5 REM 3 returns a value of 2, the expression (-5) REM 3 returns a value of -2; and the ex pre s s ion 5 REM ( - 3) ret urn s a val u E~ 0 f 2. In arithmetic expressions, PASCAL allows you to mix integers, real numbers (single and double precision), and integer subranges. When you assign the value of an expression to a variable, you must ensure that the types of the variable and the expression are compatible. In general, you can assign an integer expression to a real variable. However, you cannot assign a real expression to an integer variable. Table 3-2 Jists the type of the result for all of arithmetic operators and operands. Table 3-2: possible combinations Result Types for Arithmetic Expressions Operator (Opera t ion) Type of First Operand Type of Second Operand Type of Result ** INTEGER INTEGER INTEGER ( e x po n e n t i a t ion) INTEGER, REAL REAL, DOUBLE REAL DOUBLE INTEGER, REAL, DOUBLE DOUBLE * INTEGER INTEGER INTEGER (mul tipl ication} INTEGER REAL REAL REJ~L INTEGER, REAL REAL DOUBLE INTEGER, REAL, DOUBLE DOUBLE DOUBLE ------.------------------------------------------------------------ RE)\L, INTEGER DOUBLE / RE1\L, INTEGER REAL, (division) DOUBLE RE1\'L, DIV, MOD, REM INTEGER INTEGER 3-3 INTEGER REAL INTEGER, REAL, DOUBLE DOUBLE DOUBLE DOUBLe INTEGER INTEGER EXPRESSIONS TabJe 1-2: Result Types for Arithmetic Expressions (Cont.) Type of F'i rst Operand Type of Second Operand Type of Result +,- INTEGER INTEGER INTEGER (addition, subt.raction) INTEGER REAL REAL REAL REAL, INTEGER REAL DOUBLE REAL, DOUBLE, INTEGER DOUBLE DOUBLE DOUBLE Operator (Opera t ion) (division with truncation, modulus, and remainder) REAL, 3.1.2 INTEGER Relational Expressions A relational expression or condition tests the relationship between two expressions. A relational expression consists of two scalar or string variables or arithmetic expressions, separated by one of the relational operators listed in Table 3-3. Table 3-3: Operator Relational Operators Example Meaning A = B A is equal to B <> A <> B A is not equal to B > A > B A is greater than B >= A >= B A is greater than or equal to B < A < B A is less than B <= A <= B A is less than or equal to B Note that the two characters in each of the <>, >=, and <= operators must appear in the specified order and cannot be separated by a space. PASCAL produces a Boolean result when it evaluates a relational expression. Every relational expression therefore evaluates to TRUE or FALSE. For example, the condition 2 < 3 is always TRUE; the condition 2 > 3 is always FALSE. 3-4 EXPRES~: IONS 3.1.3 Logical Expressions Logical expressions test the truth value of combinations of conditions. A logical expression consists of two or more expressions that have Boolean results, separated by one of the logicnl operators in Table 3-4. Table 3-4: Logical Operators ---------------------------------------Operator Example Result AND A AND B TRUE if both A and B are TRUE OR A OR B TRUE if either A or B is TRUE, or if both are TRUE ----------,------------ NOT NOT A TRUE if A is FALSE, and FALSE if A is TRUE --------------------------,----The AND and OR operators combine two conditions to form a compound condition. The NOT operator reverses the truth value of a condition, so that if A is TRUE, then NOT A is FALSE. As with relational expressions, the result of a logical expression is a Boolean value. Note that the entire logical expression is always evaluated, even if the expression value could be uniquely determined from only a part of the expression. 3.1.4 Set Expressions You can use constants. Table 3-5: the operators in Table 3-5 with set variables and Set Operators Operator Example Meaning + A+B Union of sets A and B * A*B Intersection of sets A and B A-B Set of those elements of A that are not also in B A=B Set A is equal to set B <> A<>B Set A is not equal to set B <= A<=B Set A is a subset of set B >= A>=B Set B is a subset of set A IN A IN B A is an element of set B ------------------------ 3-5> EXPRESSIONS The set operators (+, *, -, =, <>, <=, and >=) require both operands to be set values. The TN operator, however, requires a set expression as its second operand and a scalar expression of the associated base type as its first operand, for example: The value of this expression is TRUE, which is a member of the set rl •. 10]. 3.1.5 because 2*3 evaluates to 6, Precedence of Operators The operators in an expression establish the order in which PASCAL evaluates the expression. Table 1-6 lists the order of precedence of the operators, from highest to lowest. Table 3-h: Precedence of Operators Operators Precedence NOT Highest ** * I, DIV, MOD, REM, AND * OR <>, <, <=, >, >=, IN Lowest PASCAL evaluates operators of equal precedence (such as + and -) from left to right. You must use parentheses for correct evaluation when you combine relational operators, for example: A (= X AND B (= Y Without parentheses, PASCAL attempts to evaluate this expression as A<=(X AND B)<=Y and generates an error. The expression needs parentheses, as follows: (A (= X) AND (8 (= y) To evaluate the rewritten expression, PASCAL compares the truth values of the two relational expressions. 3-n EXPRESSIONS You can use parentheses in any expression to force a particular of evaluation, for example: Expression: 8 * 5 DIV 2 ... 4 8 * 5 DIV (2 - 4) order Evaluates to: 16 ····20 PASCAL evaluates the first expression according to the normal rules for precedence. First, it multiplies 8 by 5 and divides the result (40) by 2. Then, it subtracts 4 to get 16. The parentheses in the second expression, however, force PASCAL to subtract before multiplying or dividing. Hence, it subtracts 4 from 2, getting -2. Then, it divides -2 into 40, with -20 as the result. Parentheses can also help to clarify an expression. could write the first example as follows: «8 For instance, you * 5) DIV 2) - 4 The parentheses eliminate any confusion about how the expression is to be evaluated. 3.2 SCOPE OF IDENTIFIERS The scope of an identifier is the part of the program in which you have access to the identifier. In a PASCAL program, the scope of a constant, type, variable, or subprogram identifier is the block in which the identifier is declared. Figure 3-1 illustrates the scope of identifiers declared at various levels. Declarations in the main program block specify global identifiers, which can be accessed in the main program and in all nested subprograms. For example, A and B in Figure 3-1 are global identifiers. They can be accessed from any level in the program. Declarations in subprogram blocks specify local identifiers. You can use a local identifier in the subprogram that contains its declaration and in all its nested subprograms. For example, the identifiers C and D are local to procedure Le~el lA and its nested subprograms Level 2A and Level 3A. You can USE~ C and D i 11 any 0 f these subprog rams, but not in the main program or in the subprograms Level_lB, Level_2B, and Level 2C. 3-7 EXPRESSIONS PROGRAM Level_.O (IN PUT, OUTPUT); VAR A,B : ] NTEGER; ··· PROCEDURE Level_1A (Z, y); VAR C,D : INTEGER; ·· · N L-e-v-e-=I-_-=2:--A:--7'(X:-7"':"')---=---=I:-7N":'::l:::-:'[:::-.:C:::-'E=::=R-:";- . FUNCTIO VAR E : REAL; ~F~'R~'O:-C~~'E~-I~IU~R~E--L~e~v-e-l-_-"3~A--<-W-)-;--------- VAR F : REAL; END; · · · < END; ") <*end procedureLevel_3A*) ------------------------------,---- ·• · <*end procedure Level_1A*) END; . ··· PROCEDURE Level_1B <V, U, T); INTEGER; VAR G F'R OCEDURE Level_2B (S, R, Q); VAR H : REAL; ·· · ENI F'R OCEDURE Level_2C (P, 0); VAR B : BOOLEAN; j : CHAR; · · · I; (*end rocedu re Leve 1._2C* > ENI P · · · <*en d procedure Level_1B*> END; ·· · <*end prograrr END. Figure 3-1: Scope of Identifiers 3-8 EXPRESSIONS Similarly, local identifiers declared in Level 1B are accessible to LevellB, Level ~~B, and Level2C, but not to Level lA, Level ?A, Level-3A, or the nain program. In general, once you define an identifier, it retRins its meaning within the block containing its declaration. You can, however, redefine an identifier in a subprogram at a lower level. If you do so, the identifier assumes its new meaning only within the scope of the redefining block. Outside this block, the identifier keeps its original meRning. For example, B is declared at program level and redefined in Level 2C. Within the scope of Level 2C, B denotes a Boolean variable. ·Everywhere else in the program,-however, B denotes Rn integer. The identifiers accessible to each routine in Figure below. 3-1 Routine Variables Main p:rog ram A, B ( :i. n t f::' ~.:.! f~ T' ) A, B ( i ntt~~tp T') r_. , 1:1 Dy E A, B ( i nte5.!e T') y C, Ay B ( i ntf.~~J(·? T' ) C, [I, [y A, B ( :i. ntf.~~~e T' ) , G ----l..evf~ll .... :LA L..f?vf?l .... :?A Level.. .. 3A LeVE' 1 __ :L B L f? V t~ 1 .. _2 B Level .... 2C , , , A, B ( integer) , (3y H A, B (Boolean) , ,J 3-9 are r.. listed CHAPTEH 4 PROGRAM HEADING AND DECLARATION SECTION The first two parts of a PASCAL program are the program heading and the declaration section. The program heading specifies the program name and the input and output files. The declaration section can contain the following sections: • LABEL declares labels for use by the GOTO statement • CONST defines identifiers constant values • TYPE defines user-defined, and pointer types • VAR declares and optionally initializes variabJes of all types • VALUE initializes variables • PROCEDURE and FUNCTION declare subprograms to represent structured, Your program need not include all these sections, but the sections that are present must appear in the order listed above. Although you can specify many labels, constants, types, variables, and subprograms, each section can appear only once in each declaration section. This chapter describes the program heading (Section 4.1), label declarations (Section 4.2), and constant defini tions (Section 4.3) • It also outlines type definitions (SE!ction 4.4), variable declarations ( Sec t ion 4 • 5), and val u e dec I a rat ion s ( Sec t ion 4 • 6) • Ch apt e r 6 describes the use of procedures and functions in detail. 4-1 PROGRAM HEADING AND 4.1 DECL~RATION SECTION THE PROGRAM HEADING The program heading begins the PASCAL program. It gives the program a name and lists the external file variables the program uses. Format [fOVERLAID1] PROGRAM program name [(filename [,filename ••• ] )] [OVERLAIDl specifies that variables with Section G.8. program name specifies the name of the program; six characters are significant. filename specifies the identifier associated external fiJe that the program uses. where: the program can share global separately compiled modules. See only the first with an The program name appears only in the heading and has no other purpose within the program. The program name cannot be redefined at program level. The file names listed in the program heading correspond to the external files that the program uses. The heading must include the names of all the external file variables. The predeclared text file variables INPUT and OUTPUT, by default, refer to your terminal (in interactive mode) or the batch input and log files (in batch mode). You must declare file variables for all other external files in the main program declaration section, and specify those variables in the program heading. Refer to Chapter 7 for more information on files. Example I PROGRAM Test1; The program heading names the program Testl, but omits the file variable list. This program does not use the terminal or any external file. Example 2 PROGRAM Sauares (INPUT, OUTPUT); The program heading names the program Squares predeclared file variables INPUT and OUTPUT. and specifies the The program heading names the program Payroll and external file variables Employee, Salary, and Output. specifies the Example 3 PROGRAM Pa~roll (EmploYee, Salar~, 4-2 Output); PROGRAM HEADING AND DECLARATION SECTION 4.2 LABEL DECLARATIONS A label makes a statement accessible from a GOTO statement. The label section must list all the labels in the corresponding executable section. Format LABEL label [,label ... ] where: label specifies an unsigned integer. When you declare more than one label, you can specify the labels in any order. The label is an unsigned integer. Labels can be listed in any order if more than one label is defined. A label can precede any statement in the program, but can be accessed only by a GOTO statement. Within the program, a colon (:) must be placed between the label and the statement. The scope of a label is the block in which it is declared. Therefore, you can transfer control from one program unit to another program unit in which the former is nested, for example: PROGRAM Trial (INPUT,OUTPUT); LABEL 7~; PROCEDURE Max; LABEL 50; BEGIN 50 WRITELN ('Testins fairness of tosses'); GO TO 75; END; (*end of procedure Max*) 75 WRITELN ('Not fair! BEGIN A weighted coin!'); END. The GOTO statement in the procedure Max transfers control to the main program statement that has the label 75. However, you cannot use a GOTO statement in the main program to transfer control into the procedure at label 50. Example LABEL 0, 6656, 778, 4352; The label section specifies four labels: 0, 6656, 778, and Note that the labels need not be specified in numeric order. 4-3 4352. PROGRAM HEADING AND DECLARATION SECTION 4.3 CONSTANT DEFINITIONS The constant section defines identifiers to represent constant values. Fo rma t CONST constant name [constant name value; value; II where: constant name specifies the identifier to be name of the constant. used as the value specifies an jnteger, a real number, a string, a Boo]ean va]ue, or the name of another constant that is already defined. Note that the value assigned to a constant identifier cannot be an expression. String values must be enclosed in apostrophes. The use of constant identifiers generally makes a program easier to read, understand, and modify. If you need to change the value of a constant, you can simply modify the CONST declaration instead of changing each occurrence of the value in the program. This capability makes programs simpler to maintain and easier to transport. Example CON~)T Ra i n Y to" a T' ~:: ~~ TRUE, 20 O:L , Pi ::: 3 .l4:1.!:j92?' C () ITlIT! a:;:: ',' p = 'United States'; Citizenship = Country; Countr~ This CONST section defines six constants. The identifier Rain is equal to the Boolean value TRUE. The identifier Year represents an integer, and Pi represents the real number 3.1415927. The identifier Comma represents a character, and the identifier Country represents a string. Characters and strings must be enclosed in apostrophes in the CONST section. The identifier Citizenship represents the symbolic constant Country and thus repr~sents a character string. Note that, since Citizenship represents a symbolic value and not a string, apostrophes are not used. 4-4 PROGRAM HEADING AND DECLARATION SECTION 4.4 TYPE DEFINITIONS The type definition introduces the name and the set of values for a type. Chapter 2 describes data types and includes examples of type definitions. Fo rma t TYPE type identifier [ type identifier type defi.nition; type defi.nition; ••. ] where: type identifier specifies the identifier to be name of the type. type definition defines a type. Figure 4-1. The types used are as the shown in Note that you can use the identifier for a previously defined type in place of the type definition for a new type. In addition, you can define packed types for arrays, records, sets, and files, as described in Section 2.5. scalar predefine scalar [ stmctu ••d EJ user-defined scalar J INTEGER enumerated ARRAY REAL sub range RECORD BOOLEAt SET CHAR FILE DOUBLE MRS-3147-83 Figure 4-1: PASCAL Data Types 4-5 PROGRAM HEADING AND DECLARATION SECTION 4.5 VARIABLE DECLARATIONS The variable declaration creates a variable and associates an identifier and a type with the variable. Optionally, the variable declaration can be used to assign an initial value to a variable. Chapter 2 describes data types and shows how to declare and initialize variables of each type. Fo rma t VAR variable name [,variable name .•. ] [variable name [,variable name ... ] : type [ : = va 1 ue n ; : type [ .:= value] ; ... ] where: variable name specifies the identifier to be used as the name of the variable. type names or defines a type. The type can be the types shown in Figure 4-1. value specifies the initial value associated with the identifier. The value must be of the same data type as the identifier. one of You can also declare packed array, record, set, and file variables, as described in Section 2.5. Note, however, that you cannot initialize file variables. 4-0 PROGRAM HEADING AND DECLARATION SECTION 4.6 VALUE DECLARATIONS The value section initializes variables that are declared in the main program declaration section. You can initialize scalar, array, record, and set variables with constants of the same type as the variable's type. The description below presents general information on value initializations. The exact format of the value initialization depen~s on the type of variable being initialized. For detailed formats and examples, refer to the section in Chapter 2 that describes the type of variable you need to initialize. Fo rma t VALUE variable name "= value; [variable name ,= value; . '.. ] where: variable name names the variable to be initialized. specify a list of variable names. You cannot value specifies a constant of the same type as the variable, or specifies a constructor for an array or record variable. You must specify a value of the correct type for each variable being initialized. You must not specify an expression. Scalar variables require scalar constants, and set variables require set constants. For arrays and record variables, you specify the value to be assigned to each element or field in a parenthesized list called a constructor. An array or record constructor must contain one constant value of the appropriate type for each component of the structure. program The value initialization can appear only in the main declaration section. You cannot use a value section in procedures, functions, or modules. 4-7 CHAPTER 5 P~SCAL STATEMENTS PASCAL provides several statements to perform the actions within the program. Any of these statements can appear anywhere in the executable part of a PASCAL program, procedure, or function. PASCAL also includes the compound statement, which allows you to group statements. This chapter presents reference information on each of the statements, organized as foJlows: comp~und • The statement • The assignment statement • Conditional statements: IF-THEN IF-THEN-ELSE CASE • Repetitive statements: FOR REP~AT WHILE • The WITH statement • The GOTO statement • The procedure call PASCAL includes simple and compound statements. A simple statement can be executed and is complete in itself; that is, it is not made up of other statements. The simple statements are the assignment statement, the GOTO statement, and the procedure call. A compound statement is an arrangement of simple statements that executes sequentially. You can use a compound statement anywhere in the program that a simple statement is allowed. This manual uses the term statement to mean either a simple or a compound statement. 5-1 PASCAL STATEMENTS Simple and compound statements can also be used in structured statements. A structured stAtement is a group of statements that can be executed either in sequence, conditionally, or repeatedly. The structured statements are the conditional, repetitive, and WITH statements. A compound stAtement can also be considered a type of structured statement. 5.1 THE COMPOUND STATEMENT The compound statement allows you to group sequential execution as n singJe statement. PASCAL statements for Format BEGIN statementl ;statement?, ... statement n; END; where: statement denotes a simple or compound statement. You can create a compound statement using any combination of PASCAL statements, including other compound statements. You must use semicolons to separate the statements that make up the compound statement; however, no semicolon is required between the last statement and the END delimiter. PASCAL treats the entire compound statement as a simple statement everywhere in the program. Examples of compound statements appear throughout this chapter. 5.2 THE ASSIGNMENT STATEMENT The assignment statement assigns a value to a variable. Format variable name 0= expression; where: variable name specifies the name of a variable of any type (except a file). It could be an array element, a file buffer variable, a function, or a field of a record. expression specifies a value, variable name, function reference, Boolean expression, set expression, or arithmetic expression. Note that the assignment operator is := in PASCAL. this operator with the equal sign (=) operator. Do not The expression on the right of the operator establishes the be assigned to the variable on the left of the operator. 5-2 confuse value to PASCAL STATEMENTS You can use the assignment statement to assign a value to a function identifier or to a variable of any type except a file. The variable and the expression must be of compatibJe types, with the following two exceptions: • You can assign an integer expression to a real variable. • You can assign an integer or single-precision real expression to a double-precision variable. For structured types, assignments. PASCAL enforces structural compatibility in Example 1 x : :: 1 ~ The variable X is assigned the value 1. Example 2 Temp := Celsius(Fahrenheit); The value returned by the function Celsius is assigned to Temp. Exampl e 3 T t::::A<B, The value of the Boolean expression A < B is assigned to T. Exampl e 4 VoweL.. Set !:::: [JA J , JE/, JJ', JO·'" JU J ]; The base The set Vowel Set is assigned the string constants shown. I I " '0', and type of VoweT Set must include the characters 'A', , E " 'U' . Example 5 M~~_ .. AT'T'a!:~[lJ :::::: M~L ... AT'r·a!:J["7] + yf)l..lT' .... AT'ra!.~[14]; The first element of My Array is assigned the sum of the element of My_Array and-the fourteenth element of Your_Array. seventh Exampl e '5 The value of each element of the array Your Array is assigned corresponding element of the array My_Array-:- to the Exampl e 7 Assume that Awardrec and New Winner are record variables of assignment-compatible types. ~his example assigns the value of each field of New Winner to the corresponding field of Awardrec. 5-3 PASCAL STATEMENTS Example q Ase~5 ::::: Asps····[ 10+".7J' Assume that the base type of the set variable Ages is the integer subrange 0 .. 255. This exampJe assigns the value of the set expression Ages- rlO+7] to the variable Ages. 5.3 CONDITIONAL STATEMENTS A conditional statement selects a statement for execution depending on the value of an expression. PASCAL provides three conditional statements: • IF-THEN statement • IF-THEN-ELSE statement • CASE statement These are described in the following sections. 5.3.1 The IF-THEN Statement The IF-THEN statement causes the conditional execution of a statement. Fo rma t IF expression THEN statement; where: expression specifies a Boolean expression. statement indicates a simple or compound statement. The statement is executed only if the value of the expression is TRUE. If the value of the expression is FALSE, program control passes to the statement following the IF-THEN statement. The THEN clause can specify a compound statement. However, note that, if you use the compound statement, you must not place a semicolon between the words THEN and BEGIN. The example below shows a semicolon immediately following the word THEN: IF Da~ = Thurs THEN, BEGIN (* misPlaced semicolon *) statement END; As a result of the misplaced semicolon, the empty statement becomes the object of the THEN clause. In this example, the compound statement following the IF-THEN statement is executed regardless of the value of Day. 5-4 PASCAL STATEMENTS Example 1 IF «X*37/Con~:;tant) Answer + Factor) :> lO()O.O THEN := Answer - Factor; If the value of the arithmetic expression is greater new value is assigned to the variable Answer. than 1000.0, a the value of A Example 2 IF (A :> B) AND ( B ~ C) THEN D ::::: A···· C; If both relational - c. expressions are true, n is assigne~ Exampl e 3 IF (Name 'SMITH') AND (INITIAL BEGIN Count I ,.J I ) THEN := Count + 1; SlTIi thadd[ Count]l ! :::: Add re~:;~:;; WFnTELN ('..} SMITH NO. I,Count, I AT L.IVE~) I This example counts the number of J SMITHs, prints each address, and stores it in an array. AddT'f.-~ss) one's street Exampl e 4 IF Day = Thurs THEN FOR I := 1 TO MaxEffip DO Pay[IJ := Salary[IJ * (l-Tax_Rate-FICA); If the current value of the variable Day is Thurs, the FOR loop is executed, and values for Pay(I] are computed. If the value of Day is not Thurs, the FOR loop is not execute~; and program control passes to the statement following the end of the loop. 5.3.2 The IF-THEN-ELSE Statement The IF-THEN-ELSE statement is an extension of the IF-THEN statement that includes an alternative statement, the ELSE clause. The ELSE clause is executed if the test condition is false. Fo rma t IF expression THEN statementl ELSE statement2 where: expression specifies a Boolean expression. sta temen tl sta tement denotes the exprt=ssion is true. to be executed if the statement2 denotes the statement expression is false. to be executed if the 5-5 PASCAL STATEMENTS The objects of the THEN and ELSE clauses can be any simple or compound statement, including another IF-THEN or IF-THEN-ELSE statement. The ELSE clause always modjfies the closest IF-THEN statement. IF A~~i THEN IF B<>l THEN C:~l E L ~; ED: c= 1 ; By definition, PASCAL interprets this BEGIN and END delimiters, as folJows: IF A:::J. THEN BEGIN IF B<>l THEN EI... SF It: :::: 1 END; statement as if it included C::"~i The variable D is assigned the value 1 if both A and B are equal to 1. Example 1 IF Ih Sf.~aSf:~ THEN WRITELN ('This person is sick.') ELSE WRITELN ('This person is health~.'); This example prints a different line of text depending on the value of the Boolean variable Disease. Note that Disease is a Boolean expression, so you need not specify Disease = TRUE. Exampl e 2 IF Balance < 0.0 THEN BEGIN WRITELN ('Overdrawn b~ ',ABS(Balance»; WRITELN ('Loan of ',Loan,' at ',Rate, , % automaticall~ deposited'); Balance := Balance t Loan; BILL_AMT := Loan (ltRate) END ELSE WRITELN ('No Loan issued this month '); WRITELN ('Balance is ',Balance); * If the value of Balance is negative, the compound statement is executed. The compound statement prints two lines of notification, adds Loan to Balance, and computes the amount of the bill for the loan. A zero or positive Balance results in a message stating that no loan was issued. The WRITELN procedure that prints the final Balance is independent of the conditional statement and is always executed. 5.3.3 The CASE Statement The CASE statement causes one of several statements depending on the value of a scalar expression. Format CASE case selector OF case-label l i s t : statement [jcase-label list statement ••• D [OTHERWISE statementi ••• D END; 5-6 to be executed, PASCAL STATEMENTS where: case selector specifies an expression that evaluates to any scal~r type except a real type. case-label list specifies one or more constants of the same type as the case selector, separated by commas. Each case-label list is associated with a statement that may be executed. The list contains the value of the case-selector expression for which the system executes the associated statement. You can specify the case labels in any order. However, the difference between the largest and smallest labels must not exceed 1000. Each case label can appear only once within a CASE statement, but can appear in other CASE statements. At run time, the system evaluates the case-selector expression and chooses which statement to execute. If the value of the case-selector expression does not appear in any case-label list, the system executes the statement in the OTHERWISE clause. If the value of the case-selector expression does not match one of the case labels and you omit the OTHERWISE clause, the status of the CHECK run-time option determines the action that the system takes. Refer to Section 8.4.3 for run-time options. If CHECK is enabled, the system prints an error message and terminates execution. If CHECK is not enabled, execution continues with the statement following the CASE statement. Example 1 CASE Ase OF 5,6 IF Birth_Month> Se? THEN Grade l= 1 ELSE Grade != 0; 7 BEGIN Grade := 2; ReadinS_Skill := TRUE END; 8 Grade:= 3 END~ At run time, the system evaluates Age and executes one of the statements. If Age is not equal to 5, 6, 7, or 8, and the CHECK option is enabled, an error occurs and execution is terminated. Example 2 CASE Ase OF 5,6 IF Birth_Month> Be? THEN Grade != 1 ELSE Grade 7 BEGIN Grade != 2; ReadinS_Skill := TRUE END; 8 ! Grade := 3 OTHERWISE Grade := 0 := 0; An OTHERWISE clause is added in this example. If the value of Age not 5, 6, 7, or 8, the value a is assigned to the variable Grade. 5-7 is PASCAL STATEMENTS Example 1 CASE Alphabetic OF 'A','E','I'p'O','U' : END; Alpha_Fla~ := Vowel~ Alpha .... Fla~:,~ != SometimE-'s OTHERWISE Alpha_Flag := Consonant "~(I : This example assigns a value to Alpha Flag depending on the the character variable Alphabetic. 5.4 value of REPETITIVE STATEMENTS Repetitive statements specify loops, that is, the repetitive execution of one or more statements. PASCAL provides three repetitive sta tements: • FOR statement • REPEAT statement • WHILE statement These are described in the following sections. 5.4.1 The FOR Statement The FOR statement specifies the repetitive execution of a statement based on the value of an automatically incremented or decremented control variable. Forma t FOR control variable -= initial value {TO } final value DO statement; DOWNTO where: control variable specifies the name of a simple variable any scalar type except a real type. of initial value specifies an expression of the same the control variable. type as final value specifies an expression of the same the control variable. type as The control variable, the initial value, and the final value must all be of the same scalar type, but cannot belong to one of the real types. The repeated statement cannot change the value of the control variable. The control variable must be a simple variable; that is, it cannot be an element of an array, a field of a record, the object of a pointer reference, or a file buffer variable. At run time, completion tests are performed before the statement is executed. In the TO form, if the value of the control variable is less than or equal to the final value, the loop is executed, and the control variable is incremented. When the value of the control variable is greater than the final value, execution of the loop is complete. 5-8 PASCAL STATEMENTS In the DOWNTO form, if the value of the control variable is than or equal to the final value, the loop is executed, control variable is decremented. When the value of the variable is less than the final value, execution of the complete. Because completion tests are performed before the executed, some loops are never executed, for example: greater and the control loop is statement is FOR Control := N TO N + Q DO Wpek r: N] :::~ We (::)k [N] + Newpa~:I' If the value of N + Q is less than the value of N (that is, negative), the loop is never execut,ed. if Q is When incrementing and decrementing the control variable, PASCAL uses units of the appropriate type. For numeric values, it adds or subtracts one upon each iteration. For values of other types, the control variable takes on each successive value of the type. For example, a control variable of type 'A' •. '2' is incremented (or decremented) by one character each time the loop is executed. If the FOR loop terminates normally, that is, if the loop exits upon completion and not because of a GOTO statement, the value of the control variable is left undefined. You cannot assume that it retains a value. Therefore, you must assign a new value to the control variable if you use it elsewhere in the program. However, if the FOR loop terminates because of a GOTO statement, it retains the value it had at termination; and you can use that value elsewhere. Example I FOR N := Lowbound TO HiShbound DO Sum := Sum + IntArra~[NJ; This FOR loop computes the sum of the elements of Int_luray with index values from Lowbound through Highbound. Example 2 FOR Year := 1899 DOWN TO 1801 DO IF (Year MOD 4) = 0 THEN WRITELN(Year:4,' IS A LEAP YEAR'); The DOWNTO form is used here to print a list of all the leap years the nineteenth century. in Example 3 FOR I := 1 TO 10 DO FOR J := 1 TO 10 DO A[I,JJ := 0; This example shows how you can directly nest FOR loops. For each value of I, the system steps through all 10 values of J and assigns the value 0 to the appropriate array element. 5-9 PASCAL STATE~ENTS Example 4 FOR Effiplo~ee BEGIN := 1 TO N DO HRS : :::: 40; FOR Da~ IF := Mon TO Fri DO Sick(Employee,Da~J THEN HR!:l : :::: HR!3····B, F' a y [: [ IT! P 1 () y f.;> f:~ J : :::: Wa ~J f:'~ [ E III P 1 D ~J e f:.~ ] END; * HI:;: S You can combine compound statements as in this example. The inner FOR statement computes the number of hours each employee worked from Monday through Friday. The outer FOR statement resets hours to 40 for each employee and computes each person's pay as the product of w~ge and hours worked. 5.4.2 The REPEAT Statement The REPEAT statement groups one or more statements for execution until a specified condition is true. Fo rma t REPEAT statement [;statement ... D UNTIL expression; where: expression specifies a Boolean expression. Note that the format of the REPEAT statement eliminates the need for a compound statement. The expression is evaluated after the statements are executed. Therefore, the REPEAT group is always executed at least once. Example REPEAT READ(X); IF (X IN (10 1 •• 1 9 1 ] ) THEN BEGIN Di~it_Count Di~it_Sum END ELSE Char_Count UNTIL EOLN(INPUT); := Di~it_Count t 1; := Di~it_Sum t ORD(X) - ORD(IOI) := Char_Countt1 Assume that the variable X is of type Char, and the variables Digit_Count, Digit_Sum, and Char Count are integers. The example reads a character (X) from the terminal. If X is a digit, the count of digits is incremented by one; and the sum of digits is increased by the value of X. The ORD function is used to compute the value of X. If X is not a digit, the variable Char Count is incremented by one. The example continues processing characters from the terminal until it reaches an end-of-line (EOLN) condition. 5-10 PASCAL 5.4.3 STATE~ENTS The WHILE Statement The WHILE statement causes one or more statements to be executed while a specified condition is true. Fo rrna t WHILE expression DO statement; where: expression specifies a Boolean expression. The WHILE statement causes the statement following the word DO to be executed while the expression is true. Unlike the REPEAT statement, the WHILE statement controls the execution of only one statement. Hence, to execute a group of statements repetitively, you must use a compound statement. Otherwise, PASCAL repeats only the single statement immediately following the word DO. The expression is evaluated before the statement is executed. If the expression is initially false, the statement is never executed. The repeated statement must change the value of the expression. If the value of the expression never changes, the result is an infinite loop. Example 1 l"'HILE NOT EOF(Filel) DO READL.N(Fil(·?l) y This statement reads through to the end of the text file Filel. Example 2 WHILE NOT EOLN(INPUT) DO BEGIN /:;:EAD(X) ; IF NOT (X IN ['A' •• 'Z','a' •• 'z','O' •• '9'J) THEN IE r T' END; ::::: E In' +1 This example reads an input character from the current line on the terminal. If the character is not a digit or letter, the error count (Err) is incremented by one. Example 1 SUITt != 0; Ntests ::::: 1; AV9 := 100; WHILE (AV9 >= 90) AND (Ntests <= Maxtests) DO BEGIN Sum := Sum + Test [Ntests]; AV9 := Sum DIU Ntests; Ntests := NTests +1 END; IF AVG <: 90 THEN WRITELN ('Your ave raSe dropped below 90 as of Test " Ntests:5); After initializing Sum to zero, this program fragment repeatedly calculates a student's average test score. When the average score falls below 90 (or NTESTS > MAXTESTS), the calculations cease. If the average score is less than 90, the system prints an informative message. 5-11 PASC~L 5.5 STATEMENTS THE WITH STATEMENT The WITH statement provides abbreviated fieJds of a record. notation for references to Fo rma t WITH record variabJe [,record variable .•. ] DO statement; where: record variable specifies the name of the record variable which the statement refers. to The WITH statement allows you to refer to the fields of a record directly instead of using the record.fieldname format. In effect, the WITH statement opens the scope of the field identifiers so tha t you can use them as you would use variable identifiers. Specifying more than one record variable has the same effect as nesting WITH statements. The names must appear in the order of their declaration. Thus, the following two statements are equivalent: WITH Cat, Dos DO Bills := Bills + Catvet + Do~vet; and WITH Cat DO WITH Dos DO Bills := Bills + Catvet + Dosvet; Note that if the record Dog is nested within the record Cnt, you specify Cat before Dog. must Example 1 RECORD Gross : REAL; Net : REAL; Bracket : REAL.; Itemized : BOOLEAN; Paid : REAL END; WITH TaNes DO IF Net < 10000.0 THEN Itemized := TRUE; This statement tests the value of the field Taxes.Net, Taxes.Itemized to TRUE if Taxes.Net is less than 10000.0. 5-12 and sets PASCAL STATEMENTS Example 2 TYPE PACKED ARRAY [1 •• 20] OF CHAR; NalTlf:~ r-~ECORD Datf.~ (Janv Feb, Mar, Apr, Ma~y Jun, Jul, Au~, Sep, Oct, Navy Dec)~ Month [I a ~:~ : Yf.,~ar' 1+ •31; : INTEGEf< [NIH VAR RECORD Hosp F' a't i ent : NaITIP; Birthdate : Datp; A~e : J NTEGEf< [ND; WITH HasP, Birthdate DO BEGIN Patient := 'THOMAS JEFFERSON , 'I. Month ::::: Ap T'; Ase : ":: 2;'56 ENIH The program segment in this example shows how you can use the WITH statement to assign values to the fields of a record. The WITH statement specifies the names of the record variables Hosp and Birthdate. The record names must be in order; that is, Hosp must precede Birthoate. The assignment statements need only specify the field names, for example: Patient instead of Hosp.Patient, Month instead of Hosp.Birthdate.Month, and so forth. 5.6 THE GOTO STATEMENT The GOTO statement directs the program to exit from a program segment before its normal termination point. loop or other Fo rma t GOTO label; where: label specifies a statement label. Upon execution of the GOTO statement, program control shifts to the statement with the specified label. The statement can be any PASCAL statement or an empty statement. The label must be defined in the declaration section. The GOTO statement must be within the scope of the label declaration. In addition, you cannot use a GOTO statement that is outside a compound statement to jump to a label that is within that compound statement. 5-13 PASCAL STATEMENTS Example FOR I := 1 TO 10 DO BEGIN IF Real_Array[IJ 0.0 THEN BEGIN Result := 0.0; GOTO 10 END; Result END; 10: := Result + 1.0/Real_Array[IJ Invertsum:= Result; This example shows how you can use the GOTO statement to exit from a loop. The loop computes the sum (Invertsum) of the inverses of the elements of Rea] Array. If one of the elements is zero however, the sum is set to-zero; and the GOTO statement forces an exit from the loop. 5.7 THE PROCEDURE CALL procedure and A procedure call specifies the actual parameters to a executes the procedure. (See Chapter fi for a complete description of procedures.) Format procedure name [(actual parameter [,actual parameter ..• ] )] where: procedure name specifies the name of a procedure. actual parameter specifies a constant, an expression, the name of a procedure or function, or a variable of any type. The procedure call associates the actual parameters in the list with the formal parameters in the procedure declaration. It then transfers control to the procedure. The formal parameter list in the procedure declaration determines the possible contents of the actual parameter list. The actual parameters must be compatible with the formal parameters. Depending on the types of the formal parameters, the actual parameters can be constants, variables, expressions, procedure names, or function names. An unindexed array name in a parameter list refers to the entire array. PASCAL passes actual parameters by the mechanism specified in the procedure declaration. 5-14 PASCAL STATEMENTS Example 1 Tollbooth (ChanSey 0.25, Lane[lJ); This statement calls the procedure Tollbooth, specifying the variable Change, the real constant 0.25, and the first element of the array Lane. ExampJe 2 This statement calls the procedure Taxes, with the expression Rate*Income and the string constant 'Pay' as actual parameters. Example 3 Halt; This statement calls the predeclared parameters. 5-15 procedure Halt, which has no CHAPTER ~ PROCEDURES AND FUNCTIONS Procedures and functions are program units that perform tasks for other program units. A procedure associates a set of statements with an identifier; the statements are executed as a group. A function returns a value. Each function 5s associated with a type and an identifier. Procedures and functions have similar structures and restrictions. This chapter uses the term subprogram in descriptions that apply to both procedures and functions. PASCAL allows you to use three kinds of subprograms: • Predeclared subprograms, described in Section 6.1. • User-declared subprograms written in PASCAL. Sections 6.2 and ~.3 present the general format of subprograms and describe how parameters are passed to subprograms. Sections 6.4 through 6.6 describe how to declare PASCAL procedures and functions. • External subprograms. This category includes subprograms written in other languages. Sections ~.7 and 6.8 describe external subprograms. You can include subprograms in the main program compilation unit, or you can compile them separately from the main program in modules. Separately compiled subprograms are considered external to the main PASCAL program, and special usage rules apply (see Section 6.8). 6.1 PREDECLARED SUBPROGRAMS PASCAL provides predeclared procedures and functions that perform various commonly used tasks, such as input and output operations and mathematical functions. These predeclared subprograms are described in the following sections. 6.1.1 Predeclared Procedures PASCAL provides procedures that perform input and output, allocate and destroy dynamic variables, supply the system date and time, pack and unpack array variables, and halt program execution. Table 6-1 summarizes these procedures. 6-1 PROCEDURES AND FUNCTIONS Table 6-1: Predeclared Procedures Procedure Parameter Type CLOSE (f) f DATE(string) string = variable of type PACKED ARRAY r 1 •• 1 1 1 0 F C HA R 1 DISPOSE (p) p DISPOSE(p, tl, ... ,tn) p = pointer variable tl, ... ,tn tag field constants Releases storage occupied by p . . ; used when p . . is a record with variants. Tag field values are optional; if specified, they must be identical to those specified when storage was allocated by NEW. FIND (f ,n) f = file variable n Moves the current file position to component n of file = file variabJe = pointer variable positive expression integer Action Closes file f. Assigns current date to string. Dea.lJocates for p ..... The variable p undefined. storage po in ter becomes f • GET (f) f HALT None Terminates execution of the program. LINELIMIT(f,n) f text file variable n integer expression Terminates execution of the program when output to file f exceeds n lines. The value for n is reset to its default after each call to REWRITE for file f. MARK (a) a a variable of type . . INTEGER Places a marker for use when allocating memory for dynamic variables. NEW (p) p Allocates storage for p.... and assigns its address to p. file variable pointer variable ~-2 Moves the current file position to the next component of f. Then GET (f) assigns the value of that component to f . . , the file buffer variable. PROCEDURES AND FUNCTIONS Table ~-l: Predeclared Procedures (Cont.) ------------,--------------------------------------------------Procedure Parameter Type Action -----------------------------,-------NEW ( p, t I , . . . , t n ) p pointer variable tl, ... ,tn tag field constants Allocates storage for p~; used when p~ is a record with variants. The optional parameters tl through tn specify the values for the tag fields of the current variant. All tag field values must be listed in the order in which they were declared. They cannot be changed during execution. NEW does not initialize the tag fields. OPEN(f, attributes) f file attributes 'rable 7-2) variable (see Opens the file f with the specified attributes. PACK ( a , i , z) a = variable of type ARRAY fm •. n] OF T i = starting index of array a z = variable of type PACKED ARRAY [u •• v] OF T Moves (v-u+l) elements from array a to array z by assigning elements afl] through a(l+v-u] to zful through z r vl. The upper bound of a must be greater than or equal to (l+v-u). PAGE (f) text f variable Skips to the next page of file f. The next line written to f begins on the second line of a new page. The default for f is OUTPUT. PUT (f) f file file variable 6-3 Writes the value of fA, the file buffer variable, into the file f and moves the current file position to the next component of f. PROCEDURES AND FUNCTIONS Table ~-l: Predeclared Procedures (Cont.) Procedure Parameter Type Action READ(f, vl, ... ,vn) f file vl, .•. ,vn variables RE~D variable For vI through vn, assigns the next value in the input file f to the variable. You must specify at least one variable (vI). The default for f is INPUT. READLN(f, vl, ... ,vn) f text file variable vl, ... ,vn variables Performs the READ procedure for vI through vn, then sets the current file position to the beginning of the next line. The variable list is optional. The default or f is INPUT. RELEASE(a) a a variable of type "INTEGER Deallocates memory allocated by the NEW procedure up to the point set by the MARK procedure. RESET(f) f f i 1 e variable Enables read i ng from file f• RESET (f) moves the current file position to the beginning of file f and assigns the first component of f to the file buffer variable, f ". EOF(f) is set to FALSE unless the file is empty. REWRITE ( f) f file variable Enables writing ~o file f. REWRITE(f) sets the file f to zero length and sets EOF (f) to TRUE. UNPACK(z,a,i) z = variable of type PACKED ARRAyru •• vl OF t a = variable of type ARRAY fm .. nl OF T i = starting index in array a Moves (v-u+l) elements from array z to array a by assigning elements z (u] through z (vl to a[i] through ari+v-u]. The upper bound of a must be greater than or equal to (i+v-u). 6-4 PROCEDURES AND FUNCTIONS Table ~-1: Predeclared Procedures (Cont.) Procedure Parameter Type Action ----------, TIME(string) string = variable of type PACKED ARRAY Assigns the current time to string. WRITE (f ,pI, •.. ,pn) f fUe pl, ... ,pn parameters variable write Writes the values of pI through pn into the file f. At least one parameter (pI) must be specified. The default for f is OUTPUT. WRITELN(f,pl, ... ,pn) f tex t: f i 1e variable pl, ... ,pn w'rite paramE!ters Performs the WRITE procedure, then skips to the beginning of the next line. The write parameters are optional. The default for f is OUTPUT. r 1 •• 1 1 1 0 F C HA R 6.1.1.1 Input/Output procedures are: • • • • • • • • • • • • CLOSE - Procedures - The Section 7.4 FIND - SE'ction 7.5 GET - Section 7.0 LINELIMI'I' - Section 7.7 OPEN - Section 7.8 PAGE - Section 7.9 PUT - Section 7.10 READ - Section 7.11 READLN - Section 7.12 RESET - Section 7.13 REWRITE - Section 7.14 WRITE - Section 7.15 • WRITELN -, Section 7.16 6-5 PASCAL input and output PROCEDURES AND FUNCT10NS 6.1.1.2 Dynamic Allocation Procedures - PASCAL provides the procedures NEW and DISPOSE for use with variables that are dynamically allocated. NEW The predeclared procedure NEW allocates memory for a dynamic variable. To refer to the dynamic variable, you must use a pointer variable. Format ~EW(p) i where: p specifies n pointer varinble. The NEW procedure sets aside memory for pA, that is, the variable that p points to. The value of pA is undefined. You cannot assume that the allocated space is initialized. For example, you declare a pointer variable as follows: VAR PTR ~INTEGER: This declares PTR as a pointer to an integer variable. The integer variable and its address, however, do not yet exist. You use the following procedure call to allocate memory for the dynamic variable: NEW(PTR); This cal] allocates a variable of type integer. The variable is A denoted by PTR , that is, the pointer variable's name followed by a circumflex(A). This call also assigns the address of the allocated integer to PTR. DISPOSE The predeclared procedure DISPOSE deallocates memory for a dynamic variable. As for NEW, you must use a pointer variable to refer to the dynamic variable. Format DISPOSE(p) i where: p specifies a pointer variable. For example, to deallocate memory for the dynamic variable above example, you can issue the following procedure call: in the DISPOSE(PTR)~ A As a result of this procedure call, the memory allocated for PTR is deallocated; and the variable is destroyed. The value of PTR is now undefined. Pointer types and dynamic allocation allow you to create linked data structures. An example of the use of pointer types and the NEW and DISPOSE procedures follows. 6-6 PROCEDURES AND FUNCTIONS This program constructs a Jinked list of records. Each student record contains data on one student, that is, a name and a student ID number. Each record also contains a field th~t is a pointer to the next record. The program reads a number and a name and assigns each of them to a field of the student record. Then, it inserts the new record on the beginning of the linked list by assigning the "Start" pointer to that new record. PROGRAM LinkedList (INPUT, OUTPUT); TYPE f:>TUDENT ... PTF~ ;::: "'~3TUDENT .... DATA; STRING PACKED ARRAY[1 •• 20J OF CHAR; NUMBER = 1 •• 99999; ~3TUDENT .,.DATI~ :::: F~E:COF~D : SlRINLH Stud_ID : NUMBER~ Next : STUDENT_PTR END; Nam(,~ VAR Startv Student : STUDENT_PTR; New .... I D : NUMBER; New_Name : STRING; Count : INTEGER, PF~OCEDURE WF~ I TE._.DATA (Studt~nt : STUDEN1._.PTH); (*This procedure prints the list of students. Because the starts at the beginnin~ of the linked list, the student names and ID numbers are printed in reverse of the order in which the~ were entered.*) printin~ VAR I,J : INTEGER; Next_Student : STUDENT_PTR; BEGIN WHITELN ('NAME:', 'STUDENT IDt:':29); REPEAT WRITELN(Student~.Name : 20, Student~.Stud_ID Next_Student := Student~.Next; DISPOSE (Student); Student := Next_Student UNTIL Student = NIL END; (* MAIN PROGRAM *) BEGIN Count ::= 0; WRITELN ('T~pe a 5-di~it ID number,' 'and a name for each student.'); WRITELN('Press CTRL/Z when finished.'); Start := NIL; WHILE NOT EOF DO BEGIN READLN <New_ID, New_Name); NEW <Student); Student-.Next := Start; Student-.Narne := New_Name; Student-.Stud_ID := NEW_ID; Start := Student; Count := Count + 1 END; IF Count > 0 THEN WRITE_DATA(START) END. 6-7 7); PROCEDURES AND FUNCTIONS In the main program, the WHILE loop reads a number and a name for one student. The following procedure call allocates memory for a new student record: NEW (!3tudent) ; The new record is inserted at the beginning of the list, that is, StudentA.Next points to the previous head of the list. The value of the new student record is assigned to the Start pointer. The WRITE DATA procedure writes the name and student ID number for each stu~ent in the linked list. After writing data for one student, the procedure assigns the address of the next record in the list to Next Student. The following call deallocates memory for one student record: 11 I SPOS[ (Sturjf.~nt) ; After deallocating memory, the procedure assigns the value of Next Student to Student. When the current student record points to NIL, the loop stops executing. NEW AND DISPOSE -- RECORD-WITH-VARIANTS FORM You can use the following forms of NEW and DISPOSE dynamic variables of a record type with variants: when manipulating NEW ( p , t 1 , . • • , t n ) DISPOSE(p,tl, ••. ,tn) The parameter p must be a pointer variable pointing to a record with variants. The optional parameters tl through tn must be scalar constants. They represent nested tag field values where tl is the outermost variant. If you create p without specifying the tag field values, allocates enough memory to hold any of the variants in Sometimes, however, a dynamic variable takes values particular variant. If that variant requires less memory allocates, you should use the NEW(p,tl, ••. ,tn) form. the system the recard. of only a than NEW(p) For example, the following record represents a menu selection: TYPE Menu_Ptr = Meat_T~pe ~Menu_Order; = (Fish, Fowl, Beef); Beef _Po rt i on ;:;; «()z _. 1 0, Oz_ .. 16, Oz_32); Menu_Order = RECORD CASE Entree : Meat_T~pe OF ( F i S tL T ~ P f.~ : ( S a 1m 0 n, Cod, P (-? r c h, T T' out ) ; Fish Lemon: BOOLEAN); (Fowl_T~pe : (Chicken, Duck, Goose); Fowl Sauce: (Orange, Cherr~, Raisin»; ( Bee f._ Ty p e : ( S tea k, R0 a~; t, P rim e _.. rib) ; Beef CASE Size : Beef_Portion OF Oz_.10, Oz_:L6 : (BeeL.. vf?~.:j : (AT'tichoke, ML·~ed»; Oz_32 : (Stomach_Cure : (Bicarbonate, Antacid,None_Needed»; END; VAR Menu_Selection 6-8 PROCEDURES AND FUNCTIONS You can allocate memory for only the Fish variant as follows: The example below shows how to call NEW and specify tag for nested variants: The tag field values must be listed in the order in declared. field which they values were The DISPOSE(p,tl, ... ,tn) procedure call releases memory occupie~ by p. The tag field values tl through tn must be identical to those specified when memory was allocated with NEW, for example: D I SPOHE (Menu .... nf:~ 1 f:~ct i on, Beef, (}::~ .... 32); This call deallocates the memory allocated by the last call shown above. NEW proce~ure 6.1.1.3 The MARK and RELEASE Procedures - The MARK and RELEASE procedures give you the opportunity to deallocate memory set aside by several NEW procedures without using several DISPOSE procedures. If you plan to allocate memory for use by several dynamic variables, you should consider placing a marker at some point. The MARK procedure places an index so that when you use the corresponding RELEASE procedure you deallocate the memory allocated after that marker. This saves you from having to DISPOSE several times, one for each NEW. The format for MARK is: Fo rma t MARK(a) where: a is a variable of type INTEGER representjng a marker. The format for RELEASE is: Format RELEASE(a) where: a is the variable specified with MARK. f)-9 PROCEDURES AND FUNCTIONS Note the following example: MAf~l\ ( A) NE l,oJ ( Mf:~ n IJ .... ~:) f? 1 (~ c t ion , F i ~;; h ) ; NEW ( Mf.~nu .... ::>E':I. f~C t i on, BE'ef , O~-::. .... :32 ) , MARK<B) NEW(Menu .... Sf~'lE'ction,Fowl) f RELEASE(A) In this example, all three NEW alJocations are deallocated by RELEASE(A). If RELEASE(B) had been specified, only the third NEW allocation, NEW(Menu_Selection,Fowl), would have been deallocated. 6.1.1.4 Miscellaneous Predeclared Procedures - PASCAL provides four miscellaneous predeclared procedures: PACK, UNPACK, DATE, and TIME. The predeclared procedures PACK and UNPACK pack and unpack arrays. Packing means that the data items are stored as densely as possible. PACK You can declare arrays to be packed by specifying PACKED in the TYPE or VAR declaration. Sometimes, however, you might want to convert an array to a packed array within the executable section of the program. The predeclared procedure PACK copies elements of an unpacked array to a packed array. Fo rma t PACK(a,i,z) where: a is a variable of type ARRAY [m .. nl i is the starting index of a. z is a variable of type PACKED ARRAY[u .• vl OF T. OF T. The number of elements in a must be greater than or equal to the number of elements in z. PACK(a,i,z) assigns the elements of a, starting with a(i], to the array z, until all of the elements in z are filled. When specifying i, keep in mind that the upper bound of a (that is, n) must be greater than or equal to i+v-u. For example, you can read integers from a file into an unpacked array, element by element, then pack the whole structure. VAR A P ARRAY[1 •• 20] OF 0 •• 15; PACKED ARRAY[1 •• 20J OF 0 •• 15; := 1 TO 20 DO READ (A[IJ); PACK (A,1,P); FOR I 6-10 PROCEDURES AND FUNCTIONS This program fragment assigns the elements AD] through Ar20] to pfll through P[201; that is, 211] the elements in A are packed into P. You can pack part of the array A as in the following example. VAR A p ARRAY[1 •• 25J OF 1 •• 1S; PACKED ARRAY[1 •• 20] OF 1 •• 15; ( *P Y'()cedu T'e c a 11 *) PACI\(A,:L ,P) v This procedure call moves elements of the array A into the packed array P. The parameter 1 specifies that the packing starts with array element An]. Thus, the elements AD1 through Ar20] are Clssigned to prll through pr20]. Packing need not start with the first element; for example, PACK (A,S,P) packs elements Arsl through Ar241 into elements P[l] through pr201. UNPACK You can convert a packed array predeclared procedure UNPACK. to an unpacked array with the Format UNPACK(z,Cl,i) ; where: z is a variable of type PACKED ARRAY[u •• v] a is a variable of type ARRAY[m .. n1 i is the starting index of a. OF T. OF T. For UNPACK, the restrictions on the array indices and the value are the same as for PACK. of i You cannot pass individual elements of a packed array to a subprogram as a VAR parameter. Therefore, you must unpack the array before you can pass its elements as VAR parameters. (* Declarations *) VAR P A PACKED ARRAY[1 •• 10] OF CHAR; ARRAY[1 •• 10] OF CHAR; PROCEDURE PROCESS_ELEMENTS (VAR CH END; (* Part of main program *) READ (P); UNPACK(P,A,1); FOR I := 1 TO 10 DO PROCESS_ELEMENTS (A[l]); 6-11 CHAR) ; PROCEDURES AND FUNCTIONS This program fragment reads characters into the packed array P. The procedure call to UNPACK assigns Prl] through PrIOl to the unpacked array elements AD] through ArlOl. Then, for each ca11 to PROCESS_ELEMENTS, one element of A is passea to the procedure. DATE AND TIME The predeclared procedures DATE and TIME assign the current time to a string variable. date and ARRAyrl .. 11] OF Fo rma t DATE(string); TIME(string) ; where: string specifies a variable of CHAR. type PACKED The folJowing example demonstrates the use of DATE and TIME: (* Declarations *) T()da~3S __ Da te, CI..I l' rent . _Time PACKED ARRAY[1.+11J OF CHAR; (* Procedure calls *) DATE(Toda~5_Date)~ TIME(Current_Time); These two calls return results in the following format: 19-Jan--1980 14:20:25 The time is returned in 24-hour format. Thus, the time shown above is 14 hours, 20 minutes, 25 seconds. In the DATE procedure, if the day of the month is a I-digit number, the leading zero does not appear in the result; that is, a space appears before the date string. 6.1.2 Predeclared Functions PASCAL provides functions that compute arithmetic values, test certain Boolean conditions, transfer data from one type to another, and perform other miscellaneous calculations. Predeclared functions return a value as a resuJt. Table 6-2 summarizes the predeclared functions. Arithmetic functions perform mathematical computations. Parameters to these functions can be integer, real, single-precision, 01 double-precision expressions. The arithmetic functions, except for the absolute and square root functions, return a real value when the parameter is an integer, single-precision, or real value. When the parameter is a double-precision expression, the result is a double-precision value. The absolute and square root functions return a value of the same type as the parameter. 6-12 PROCEDURES AND FUNCTIONS Boolean functions return Boolean values after testing a condition. The EOF and EOLN functions operate on files: EOF tests for the end-of-file condition on a variable of any file type, and EOLN tests for the end-of-line condition on a text file variable. The ODD function tests whether an integer parameter is odd or even. The UNDEFINED function, for which you must supply a real value, returns the value TRUE when the argument is not in normalized floating-point format. Variables containing a value that is not in a normalized floating-point format cause a reserved operand fault when used in arithmetic computations. Transfer functions take a parameter of one type and return the representation of that parameter in ~nother type. For example, the ROUND function rounds a real number to an integer, and TRUNC truncates a real number to an integer. The miscellaneous functions include PRED and SUCC. The PRED and SUCC functions operate on parameters of any ordered scalar type (that is, all scalar types except one of the renl types). SUCC returns the successor value in the type; PRED returns the predecessor value. Table 11-2: Predeclared Functions Category Function Parameter Result Type Type Purpose Arithmetic ABS (n) integer, rea I, double same as n Computes the absolute value of n. The type of n must be either integer, real, or double; nnd the type of the result is the type of n. ARCTAN (n) integer, real, double real double Computes the arctangent of n. COS (n) integer, real, double real double Computes cosine of n. EXP (n) integer, real, double real double Computes e**n, the exponential function. LN (n) integer, real, double real double Computes the natural logarithm of n. The value of n must be greater than o. SIN (n) integer, real, double real double Computes of n. 6-13 the the sine PROCEDURES AND FUNCTIONS Table 6-2: Category Boolean Predeclared Functions (Cont.) Function Parameter Result Type Type Purpose SQR (n) in teg er , rea] , doub1e same as n Computes n**2, the square of n. The type of n must be either integer, real, or double; and the type of the result is the type of n. SQRT (n) in teg e r , rea 1, double real double Computes the square root of n. If n is less than zero, PASCAL generates an e r ro r . EOF (f) file variable Boolean Indicates whether the file position is at the end of the file f. EOF(f} becomes TRUE only when the file position is after the last element in the file. The default for f is INPUT. EOLN (f) text file Boolean variable Indicates whether the position of file f is at the end of a line. EOLN (f) is TRUE on]y when the file position is after the last character in a line, in which case the valur of fA is a space. The default for f is INPUT. ODD {n} integer Boolean Returns TRUE if the integer n is odd; returns FALSE if n is even. UNDEFINED {r} real, double Boolean if Returns TRUE the value of r is a not in normalized floating-point fo rma t. 6-14 PROCEDURES AND FUNCTIONS Table ~-2: Predeclared Functions (Cont.) Category Function Parameter Result Type Type Transfer CARD (s) set integer Returns the number of elements currently belonging to the set s. CHR (n) integer char Returns the character whose o r din a ] n urn be r i s n (if it exists). ORD (n) any scalclr type except a real type integer the Ret.urns ( integer) ordinal value corresponding to the value of n. HOUND(n) real, double integer Rounds the real or double-precision value n to the nearest integer. SNGL(d) double rea] Rounds the double-precision real number d to a single-precision rea 1 n urn b e r • 1:'RUNC (n) rea I , double in teg e r Truncates the real or double-precision value n to an integer. CLOCK none integer Returns an integer value equal to the central processor time used by the current process. The time is not expressed in milliseconds. EXPO ( r) real" double integer Returns the integer-valued exponent of the binary floating-point representation of ri for example, EXPO{8.0) is 4. Miscellaneous ~-15 Purpose PROCEDURES AND FUNCTIONS ~-2: Table Predeclared Functions (Cont.) Category Function Parameter Result Type Type PRED(a) any scalar type except a r eaJ type Purpose same Returns the type as predecessor value parameter in the type of a (if a predecessor exists). But it is up to you to make sure there is pred/succ. The compiJer will always return with the next ordinal value higher/lower than a. There is no bounds checking. Checking 0ccurs only if the PRED(a) or SUCC(a) is in an ass ignmen t statement, for example: (*$CHE~K+*) x: =PRED (a) SUCC(a) any same scaJar type as type parameter except a real type Returns the successor value in the type of a (if a successor exists) . arithmetic routines available with PASCAL also provides additional PASLIB, the PASCAL library. Use the following format to specify a routine from the Common Math Library: FUNCTION routine name (VAR parameter list): reSUl t type;} { FORTRAN where: routine name is one of the names listed in Table ~-3. parameter list are acceptable arguments for this routine. See the TOPS-IO/TOPS-20 Common Math Library Reference Manual. result type is the type of the function result. Table ~-3 lists these routines and their purpose. For more information concerning these routines, refer to the TOPS-IO/TOPS-20 Common Math Library Reference Manual. 6-16 PROCEDURES AND FUNCTIONS Table h-3: Library Routines Routine Name Purpose ARCOS arc cosine AINT truncation to integer ALOG natural logarithm ALOGlO base-l0 logarithm AMAXO largest of a series AMINO smalJest of a series AMINI smallest of a series AMOD rE!mainder ANINT nearest whole number ASIN a roc sine ATAN2 arc tangent of two angles COSD cosine (angle in degrees) COSH hyperbolic cosine COTAN contangent DABS double-precision D-floating-point absolute value DACOS double-precision D-floating-point arc cosine DASIN doubJe-precision D-floating-point arc sine DATAN doubJe-precision D-floating-point arc tangent DATAN2 double-precision t\ol70 angles DBLE conversion from single-precision doubJe-precision D-floating-point format DCOS double precision D-floating-point cosine DCOSH double-precision D-floating-point hyperbolic cosine DCOTAN double-precision D-floating-point cotangent DDIM d 0 ubI e- prE! cis ion differenCE! DEXP double-precision D-floating-point exponential DEAXP2. exponentiation of a double-precision D-floating-point number to the power of an integer D-floating-point arc D-floating-point 6-17 tangent of to positive PROCEDURES AND FUNCTIONS Table G-3: Library Routines (Cont.) Routine Name Purpose DEAXP 1. exponentiation of a double-precision D-floating-point number to the power or another double-precision D-floating-point number. DFLO,l\T conversion of an integer D-floating-point format DIM positive difference )INT double-precision D-floating-point truncation double-precision to ,OG double-precision D-floating-point natural logarithm DLOGIO double-precision D-floating-point base-IO logarithm DMAXl double-precision series D-floating-point largest in a DMINl double-precision series D-floating-point smallest in a DMOD double-precision D-floating-point remainder DNIN'T double-precision number DPROD double-precision D-floating-point prod uc t DSIGN d 0 ubI e- pre cis ion D-floating-point transfer of sign DSIN double-precision D-floating-point sine DSINH double-precision D- fl oa t i ng- po in t hyperbolic sine DSQRT double-precision D-floating-point square root DTAN d 0 u b 1 e- pre cis ion D- fl oa ti ng-po in t tangent DTANH double-precision tangent D-floating-point EXPI. exponentiation of another integer an EXP2. exponentiation of a single-precision number to the power of an integer EXP3. exponentiation of a single-precision number to the power of another single-precision number FLOAT conversion of an integer to single-precision format lABS integer absolute value lDIM integer positive difference D-floating-point 6-18 integer to nearest whole hyperbolic the power of PROCEDURES AND FUNCTIONS Table ~-3: Library Routines (Cont.) Routine Name Purpose IDINT conversion of a dobule-precision D-floating-point number to integer format IDNINT integer nearest whole number for a double-precision D-floating-point number IFIX conversion fo rma t of a single-precision number to integer INT conversion format of a single-precision number to integer ISIGN integer transfer of sign MAXO largest of a series MAXI largest of a series MINO smallest of a series MINI smallest of a series MOD integer remainder MINT integer nearest whole number for a single-precision number RAN random number generator RANS random number generator with shuffling REAL conversion of an integer to single-precision format SAVRAN save teh last random number generated SETRAN set the seed value for the random number generator SIGN transfer of sign SIND sine (angle in degrees) SINH hyperbolic singe SNGL conversion of a double-precision D-floting-point number to single-precision format TAN tangent TANH hyperbolic tangent 0-19 PROCEDURES AND FUNCTIONS 6.2 FORMAT OF A SUBPROGRAM Subprograms are similar in format to programs. A subprogram consists of a heading and a block; the block contains a declaration section and an executable section. The heading specifies the name of the subpYogram and lists its formal parameters. For a function, the heading also indicates the type of the value returned. The declaration section defines labels and identifiers for constants, types, variables, procedures, and functions that are used in the subprogram. The executable section contains the statements that perform the actions of the subprogram. The labels and identifiers declared in the subprogram are local data and are unknown outside the scope of the subprogram. The system does not retain the values of local variables after exiting from the subprogram. The following is a sample subprogram: PROCEDURE PRINT_SYM_ARRAY (VAR A: ARR; Side: INTEGER); (* This procedure prints arra~ A if it is !=j \;1 mIII e t T' i c (which :i.~:; determined b~ the function SYMMETRY). The a T' r'a~:1 i ~:; F' T' i nted in row order, one row per line. *) VAR I, J, K, L : INTEGER; FUNCTION SYMMETRY : BOOLEAN; (* This function returns true if the other'wisf~'. arra~ is s~mffietric; false *) BEGIN SYMMETRY := TRUE; FOR K := 1 TO Side DO FOR L := K TO Side DO IF A[K,LJ <> A[L,KJ THEN SYMMETRY := FALSE; ENIH BEGIN IF SYMMETRY THEN BEGIN WRITELN (IArT'a~ entered: I ); FOR I := 1 TO Side DO BEGIN FOR J := 1 TO Side DO WRITE (A[I,JJ : 4 ); WRITELN ENIH END ELSE WRITELN (IThe END; aT'T'a~ is not s~ffimetT'ic+I); Subprograms can be nested within other subprograms. In the previous example, the function SYMMETRY is nested in the procedure PRINT SYM ARRAY. The order of nesting determines the scope of an identTfier. 6-20 PROCEDURES AND FUNCTIONS Data items declared in any particular block of a PASCAL program are considered global to all its nested subprograms. Thus, d~ta items declared in the main program block are global to alJ subprograms. A subprogram can access its global identifiers. For example, the function SYMMETRY above has no local variables. Tt uses the global identifiers K and L, and the parameters A and Side, which are declared in PRINT SYM ARRAY. 6.3 PARAMETERS Subprograms communicate data with the main program and with each other by means of parameters. A subprogram can have any number of parameters, but need not have any at all. The subprogram heading lists the forma] parameters, which specify the type of data that will be passed to the subprogram. For example, the formal parameter list for the procedure PRINT SYM ARRAY is the following: (VAR A ARR; Side: INTEGER) This Jist specifies two parameters to be passed to PRINT SYM ARRAY: the variable A of the previously defined type ARR, and the-~al~e Side of type INTEGER. Each formal parameter corresponds to an actual parameter, specified in the subprogram call. For example, a valid procedure call to PRINT_SYM_ARRAY is the following: This procedure call passes the variable Current Arr and the Current Side to PRINT SYM ARRAY. value of The formal parameters are identifiers used in the subprogram; they represent the actual parameters in each subprogram call. You can call a subprogram several times with different actual parameters. At execution, each formal parameter represents the variable or value of the corresponding actual parameter. The formal-value parameters, and the actual parameters to which they correspond, must be of identical types. 6.3.1 Formal Parameters The formal parameter list specifies the identifier for each parameter and the type of each parameter to be used within the subprogram. Format ( [ [mechanism specifier ] [ mechanism specifier] identifier list identifier list n-21 type; type .•. ] ); PROCEDURES AND FUNCTIONS where: mechanism specifier indicates how PASCAL passes data to this parameter. The mechanism specifiers for PASCAL subprograms are VAR, PROCEDURE, and FUNCTION. identifier list specifies one or more separated by commas. type specifies the type of the parameters in the list. You can pass values, variables, procedures, and functions to a subprogram written in PASCAL, as described below. PASCAL provides subprograms. two methods for passing identifiers, parameters to PASCAL 1. Value -- the value of the actual parameter expression is passed to the subprogram. The subprogram cannot change the actual parameters's value during execution. (Value is the default method.) 2. Variable -- the address of the parameter variabJe is passed to the subprogram. The subprogram can change the parameter's value. The VAR mechanism specifier indicates that a parameter is to be passed as a variable parameter. Value parameters pass the value of the actual parameter expression to the subprogram. The subprogram does not change the actual parameter's value during execution. Therefore, after the subprogram executes, the value of the actual parameter is the same as before the execution of the subprogram. The following example shows a formal parameter list that includes two value parameters: INTEGER; PROCEDURE EXAMPLE (Counter NAME Variable parameters pass the address of the actual parameter expression to the subprogram. The subprogram can change the actual parameter's value. Therefore, after the subprogram executes, the value of the actual parameter is the value assigned to the corresponding formal parameter within the subprogram. To specify a variable parameter, use the reserved word VAR before the parameter in the formal parameter list. The following example shows the same formal parameter list as in the previous example. In this example, the parameters have been defined to be variable parameters. PROCEDURE EXAMPLE (VAR Counter INTEGER; VAR Name: CHAR); 6.3.1.1 Value Parameters - By default, PASCAL passes value parameters to PASCAL subprograms. When you specify a value parameter, the formal parameter list does not include the reserved word VAR. The actual parameter corresponding to a formal value parameter must be a compatible expression. Value parameters follow the rules for assignment compatibility. For example, the following list passes all parameters by value: INTEGER; C CHAR) 6-22 PROCEDURES AND FUNCTIONS integer The actual parameters corresponding to A and B must be expressions. The actual parameter corresponding to C must be a character expression. If the subprogram changes the value of a value parameter, the change is not reflected in the calling program unit. Thus, if you do not want the value of an actuaJ parameter to change as a result of the execution of a subprogram, you pass it as a value parameter. 6.3.1.2 Variable Parameters - To pass a variabJe parameter, use the reserved word V~R. You must use the VAR specifier to pass file parameters and to pass actual parameter variables with values that change during execution of the subprogram. The corresponding actual parameter must be a variable; it cannot be a constant or an expression. When you pass a variable as a variable parameter, the subprogram has direct access to the corresponding actual parameter. Thus, if the subprogram changes the value of the formal parameter, this change is reflected in the actual parameter in the calling program unit. In the example procedure PRINT_SYM_ARRAY, the actual parameter corresponding to A is passed using variable semantics. It must be a variable of the previously defined type, ARR. The actual parameter corresponding to Side is passed by value and must be an integer expression. The VAR specifier must precede each identifier list that is to be passed using variable semantics. Thus, VAR can appear more than once in the formal parameter list, for example: (VAR SEA, BREEZE: REAL; WIND: INTEGER; VAR SICK As a result of this formal parameter list, the actual parameters corresponding to SEA, BREEZE, and SICK are passed as variable parameters; and the actual parameter corresponding to WIND is passed as a value parameter (the default) • Compatibility Variables passed to a subprogram as actual variable parameters must be of the same type as the corresponding formal parameters. The following restrictions also apply to variable parameters: • You cannot pass an element of a packed structure with the VAR specifier, although you can pass the entire structure. You must unpack the structure or assign its elements to simple variables before you can pass individual elements. • You cannot pass a variable of a packed set type to a formal parameter that is an unpacked set type, and vice versa. • You cannot pass a tag field of a record with the VAR specifier (see Section 2.3.2.1). You can pass the entire record or assign the tag field to another variable in order to pass it. ~-23 PROCEDURES AND FUNCTIONS 6.3.1.3 Formal Procedure and Function Parameters - PASCAL allows procedures and functions to be passed as parameters to other procedures or functions. To do this, a full procedure or function heading is given as one parameter of the procedure being declared. For example, the following procedure declaration specifies one value parameter and one function parameter: F' f~ 0 CE DU I:~ E ACT U A L. VAL. (V Al..! J NT EGE r~ , FUNCTION FORMAL. (Fl:INTEGER):INTEGER); := FORMAL (VAL + 1), The formal function parameter takes one value integer parameter, and returns an integer value. When procedure ACTUAL is called, you need to supply it with two parameters: an integer value; and, the name of a function which takes one integer argument and returns an integer value. Note that ONLY the function name is passed to the procedure; do NOT supply the function's parameters in the procedure call. They are supplied when the procedure calls the function. The parameter list of the formal procedure or function may consist of anything that can be defined in a normal procedure or function declaration, including value parameters, VAR parameters, conformant arrays, and even other procedures and functions. These procedures and functions obey the same rules as the formal procedure or function of which they are a parameter. The following is an example of procedures nest~d to two levels: a procedure heading with formal PROCEDURE OUTER(PROCEDURE FORMAL1(FUNCTION FORMAL2:REAL, B:REAL», Procedure OUTER has one parameter, a procedure. This procedure has two parameters, a real-typed function (with no parameter.s) and a real value parameter. When a subprogram is called with a procedure or function parameter, the parameter lists of the formal and actual parameters must be congruous. This means that the parameter lists must have the same number of parameters; and each corresponding parameter must be of the same kind (value, VAR, etc.) and of the same type. In the following example, procedure YOU BET could be passed as a parameter to procedure OUTER above, because Y5U BET and FORMALl have congruous parameter lists. PROCEDURE YOU_BET(FUNCTION YOU: REAL, BET: REAL), In the following example, procedures PRINTHEX and PRINTOCTAL have congruous parameter lists. Procedure PRINTBINARY's parameter list is not congruous to either of the others because both of its parameters are value parameters. PROCEDURE PRINTHEX (VAL: INTEGER, VAR SIZE: INTEGER), PROCEDURE PRINTOCTAL. (I: INTEGER, VAR F: INTEGER), PROCEDURE PRINTBINARY (NUM: INTEGER, WIDTH: INTEGER), f)-24 PROCEDURES AND FUNCTIONS An optional syntax for formal procedure and function parameters is to omit the parameter list in the declaration. If this is done, no checking on the number or type of parameters is possible, and only value parameters are allowed when calling the formal procedure or function. No conformant array, procedure, or function parameters can be passed to a formal procedure or function unless they are explicitly declared. For information on calJing sequences for procedures, refer to Appendix G. 6.3.2 user-defined functions and Conformant Arrays Some programming applications require general subprograms that can process arrays of varying size. PASCAL allows you to declare such subprograms using conformant arrays. You can call the subprogram with arrays of different sizes, as long as their bounds are within those specified by the formal parameter. For example, you could write a procedure that sums the components of a one-dimensional array. Each time you use the procedure, however, you might want to pass arrays with different bounds. Instead of declaring multiple procedures using arrays of each possibJe size, you can use a conformant-array parameter. The procedure treats the formal parameter as if its bounds were those of the actual parameter. The format of a conformant-array parameter is: array id ARRAyridlow •. idup : scalar-type id] OF conformant-array type; where: idlow is the lower bound constant identifier idup is the upper bound constant identifier array id is one or more array identifiers associated with the Idlow and idup are bound identifiers. They define the lower and the upper limits, respectively, of the array. Each id is treated as a constant value in the subprogram; therefore, you cannot assign values to the id other than in the definition. You cannot use a subrange to define the limits. Scalar type specifies the data type of the index. Note that you must use a type identifier to specify the range of indices. The type identifier can be one of the predefined scalar types INTEGER or CHAR. Conformant-array type can be either conformant-array specification. 6-25 a type identifier or another PROCEDURES AND FUNCTIONS Multidimensional arrays can also use conformant array parameters. fo rma tis: The array-id : ARRAY ridlow •• idup : scalar-type idl OF ARRAY ridlow •. idup : scalar-type idl OF conformant-array type; An abbreviated form can also be conformant arrays. The format is: used to define multidimensional array-id : ARRAY [idlow •• idup : scalar-type id; i dn •. idn : scalar- type idn; .•• ] OF conformant-array type; When a subprogram with conformant-array parameters is called, the IDs (the bound identifiers) assume the values of the lower and upper bound values of the actual parameters. These values are those specified in the definition section of the actual-array parameter. A conformant-array parameter can have up to one conformant dimension packed. This means that a one-dimensional conformant-array parameter can be packed or unpacked. A multidimensional conformant-array parameter can be unpacked, or its last (rightmost) conformant dimension can be packed. Note that this restriction applies only to the conformant part of the parameter; the conformant array type can be of any type, packed or unpacked. The components and indices of the actual and formal conformant-array parameters must be of compatible types. The rules for conformant-array compatibility are the same as those for other arrays with one exception. That is, the range of the index types of the actual-array parameter must be within the range specified for the formal parameter. 6-26 - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - ------------ PROCEDURES AND FUNCTIONS Example 1 The following program shows how to declare parameters. and use conformant-array PROGRAM D~narr(INPUT~ OUTPUT); (* Th i~:; p Y' 0 !,:,! T' a IT! ill u E t rat f:'~ ~:; t h f.~ U S (~ 0 f e D n f 0 T' IT! ant .... a T' T' a ~:~ paraITlf.,-ters. The PY'ocedure SUIT! is called from the main program with two d i ffp r.:~nt actua I pa T'amet(,:,~ r~:;: AT' l':L and AT' T'2. *) 1 ~:-;O , TYPE Rn~,~ ARRAY[1 •• 5J OF INTEGER; VAR AT'r1 ARRAY[7 •• 20J OF INTEGER, AT'r2 K,J ! INTEGER, t • PROCEDURE Sum (VAR InarT' : ARRAY [Low •• High : INTEGER] OF INTEGER), (* This proceduY'e accepts actual-arT'a~ parameters with intpgpr components whose indices are within the range specified b~ Rng. *) VAF, I, Ans INTEGER, BEGIN Ans :== 0; FOR 1:= Low TO High DO An ~j : =~ ~~ I"'I~) + I naT' T' [ 1 :] ; WRITELN('The sum of the components is: ',Ans) END, (*end Sum*) (* MAIN PROGF~AM *) BEGIN WRITELN ('TYPE 5 INTEGERS'), FOR K:= 1 TO 5 DO READ (AT'r10\]); Sum (A r 1':L ) ; WRITELN('TYPE 14 INTEGERS'); FOR J:= 7 TO 20 DO READU~rr2L.J]) ;. Sum (Arl~2) END. This program sums the components of the arrays Arrl and Arr2. The procedure Sum includes a I-dimensional conformant-array parameter, Inarr, whose indices are of type Rng. Within the main program, Sum is called with two different arrays: Arrl with index type (1 •• 51, and Arr2 with index type [7 •• 20]. The first procedure call, Sum(Arrl), passes Arrl to Sum. Low assumes the value of 1, and High assumes the value of 5. The FOR loop processes array components Inarr[ll to Inarrr5]. When Sum is called with Arr2, Low assumes the value of 7, and High assumes the value of 20. When Sum is called with Arr2, the FOR loop processes the components Inarr[7] to Inarr[20]. 6-27 PROCEDURES AND FUNCTIONS Example 2 A conformant-array parameter can have more than one ~imension, this example: TYPE Level_Ran~e as in = 1 •• 6; Ne 1 aSSE-:·~~:; ::" 1 •• 8, Nstudents = 1 •• 40~ Names = PACKED ARRAY [1 •• 35J OF CHAR; VAR ~)tudents : AF\f~AY F' r~ 0 CEIl U R E 1\ i d .... C () U n t [1 •• 6,1 •• 0,1 •• 40] OF NalllE'S' (!; c h (.1 () 1 : A F~ I:~ A Y [: L (-::' V f? 1 .... L.. 0 w. • L.. (.:~ vel .... H :i. ~.:.~ h L..evel_Ran~e; : Nclasses_L()w •• Nclasses_Hi~h N 5 t IJ d €.~ n t tIl... 0 w. • N ~:) t u d f:~ n t .... H i ~.~ h : : NstudentJ OF Names); N cIa s 5 f? S ' This example defines School as a three-dimensional conformant-array parameter. Each array passed to School mjght contain the names of all the students in a particular elementary school. The indices of the array denote the number of grades in the school, the number of classes at each grade level, and the number of students in each class. The actual-array parameters can have from one to six grades, one to eight classes at any grade level, and one to forty students in any particular class. Furthermore, the indices of the actual-array parameters must be within the ranges shown in the TYPE section. For example, a school with six grades must use integer indices from one to six. Indices of zero to five, for instance, cannot be used. 6.4 DECLARING A PROCEDURE A procedure is a group of statements that perform a set of actions. The use of procedures allows you to break a complex program into several units, each of which performs one task. For example, a program that computes social statistics from survey data might contain procedures to input and validate the data, select a random sample, and print results. To declare a procedure, specify its header and block in the procedure and function section. The header consists of the word PROCEDURE and the procedure name along with any parameters you want to include. The block consists of its own declaration section and the executable section. You can declare a procedure in the main program, in a module, or in another subprogram. /5-28 PROCEDURES AND FUNCTIONS Fo rma t 1 PROCEDURE procedure-identifier [(formal parameters)] label section; constant section; type sec t ion;; variable section; procedure-and-function section; BEGIN statement [; END; statement .... ] Format 2 f[ r[.GLOBAL] TI} PROCEDURE procedure id [(formal parameters)] FORTRAN 1 lJ , [FORWARD; ] Format 3 PROCEDURE procedure id [(formal parameters)] ;{[EXTERN [AL] ; TIl. FORTRAN; lJ ( Format 1 shows the format for a procedure that is included within program that calls it. the Format 2 shows the format for a procedure that can be called externally, that is, it can be called from another program. The FORWARD declaration permits the use of forward references in the declarations section. Forward declarations are described in Section 6.6. The FORTRAN declaration at the beginning .of the 1ine indicates that this procedure can be called externally by a FORTRAN program. Format 3 shows the format for a procedure that is being called externally. The procedure must be compiled separately from the source program that calls it. Placing the FORTRAN declaration at the end of the line indicates that the procedure being called by PASCAL is a procedure written in the FORTRAN language. Refer to Section ~.7. procedure id specifies the identifier to be used as the name of the procedure. formal parameters contains the names and types of the formal parameters. It optjonally can include reserved words VAR, PROCEDURE, and the FUNCTION. label section declares local labels. constant section defines local constant identifiers. type section defines local types. 6-29 PROCEDURES AND FUNCTIONS variable section declares local v~riables. procedure-and-function section declares local procedures and functions. s ta temen t specifies procedure an action to be performed by the procedure. A can contain any of the statements described in Chapter 5. A procedure consists of a heading and a block. The procedure block is similar in structure and contents to the main program block, with the following exceptions: • The declaration section cannot contain VALUE initializations. • The procedure block ends with END followed by a semicolon (i), rather than a period (.) as in the main program. The procedure does not have a block if it is a forward declaration or is defined externally (EXTERNAL or FORTRAN). to the procedure, You must declare all the variables that are local but you should not redeclare the formal parameters or the procedure identifier as variable, type, or constant identifiers. For the two examples that follow, assume that these declarations been made: CONST NUMBER = 20; TYPE Range = 0 •• 100; List = ARRAY[l •• NUMBERJ OF VAR have Ran~e; ARF~ : List; Min i IlIU Ill' Ma ~·d III u tTl Ave T'age : r~EAI...; Example 1 PROCEDURE READ_WRITE (VAR A List); VAR I : INTEGER; BEGIN WRITELN ('Type a list of 20 integers', 'in the range of 0 to 100.'); FOR I := 1 TO Number DO BEGIN READCA[IJ); WRITE(A(IJ!7); WRITELN END END; The procedure READ WRITE reads a list of into the array A,-and writes the array. parameter, the array A. 20 integers, inserts them READ WRITE uses one variable Given the declaration of ARR, the following is a valid procedure call: READ_WRITECARR); 6-30 PROCEDURES AND FUNCTIONS As a result of this call, the list of integers is written in the array ARR. The value of this array is then returned to the program unit that called the procedure READ WRITE. Example 2 PROCEDURE MIN_MAX_AVG (VAR Miny Max : Ran~e; VAR Avg : REAL; A : List); VAR Sum, NMax~ NMin~ J : INTEGER; BEGIN M3X := Ael); Min:= Max; Sum:= Max; NMax := 1; NMin:= 1; FOR J := 2 TO NUMBER DO BEGIN Sum := Sum + A[JJ~ IF A[J) > Max THEN BEGIN Max := AeJJ; NMa>: : =:: 1 END ELSE IF A[JJ = Max THEN NMax := NMax + 1; IF AEJJ < Min THEN BEGIN Min := A[J); NMin !:=: 1 END Min THEN ELSE IF A[JJ NMin : :~: NMin + 1 END; AVG := Sum/NUMBER; WF~ I TELN; WRITELN('Maximum =',Max:4,', occurring',NMax:4, , times'); WFnTELN; WRITELN('Minimuffi =', Min:4,', occurring', NMin:4,' times'); WFnTELN; WRITELN ('Average value (truncated) =', TRUNC(Avg):10); WRITELN ('Average value ='r Avg : 20) END; This procedure computes the minimum, maximum, and average values in array A. It also counts the number of times the minimum and maximum values occurred, and stores those numbers in NMin and NMax. The WRITELN statements print the results of each of those computations. Min, Max, and Avg are formal variable parameters. Their values, as assigned in the procedure MIN_MA.X_AVG, are returned to the calling program unit and can be used for further computations in the program. A is specified as a value parameter because its value does not change in the procedure. The following is a valid procedure call to the procedure: The values of the formal parameters Min, Max, and Avg are returned to the actual parameters Minimum, Maximum, and Average, which were defined in the main block of the program. 6-31 PROCEDURES AND FUNCTIONS 6.5 DECLARING A FUNCTION A function is a group of statements that compute a scalar or pointer value. To declare a functjon, specify its heading and block in the procedure and function section. Format 1 FUNCTION function id [(formal parameters)] :result type; labe] sect jon; constant section; type section; variable section; procedure-and-function section; BEGIN statement END; [;statement ... ] Format 2 [GLOBAL] 11 I( FUNCTION function id {IT [FORTRANl lJ Fo rma t [( forma1 parameters)] [FORWARD;D 3 FUNCTION function id [(formal parameters)] ;{[EXTERN [AL] FORTRAN; Format 1 shows the format for a function that is included program that calls it. ;ll} lJ within the Format 2 shows the format for a function that can be called externally, that js, it can be called from another program. Placing the FORTRAN declaration at the beginning of the line indicates that a FORTRAN program can call this procedure. The FORWARD declaration permits the use of forward references in the declarations section. Forward declarations are described in Section h.n. Format 3 shows the format for a function that is defined externally; the procedure is compiled separately from the source program that calls it. Placing the FORTRAN declaration at the end of the line indicates that the procedure being called by PASCAL is written in the FORTRAN language. Refer to Section h.7. function id specifies the identifie~ to be used as the name of the function. formal parameters contain the names and types of the formal parameters. They optionally can include the reserved words VAR, PROCEDURE, and FUNCTION. result type specifies the type of the function's result. a scalar or pointer value. f5-32 The result must be PROCEDURES AND FUNCTIONS label section declares local labels. constant section defines local constant identifiers. type section defines local types. variable section declares local variables. procedure-and-function section declares local procedures and functions. statement specifies an action to be performed by the function. A function can contain any of the statements oescribed in Chapter 5. A function must contain a statement that assigns a value to the function ioentifier (for every potential path through the code). If it does not, the value of the function could be undefined. A function consists of a heading and a block. The formal parameter list in the function heading is identical in format to the list in the procedure heading. The function block is similar in structure and contents to the main program, with the following exceptions: • The function cannot contain a value initialization section . • The function block ends with END followed by a semicolon (;), rather than a period (.) as in the main program. The function does not have a block if it is a forward declaration, or if it is defined externally (EXTERN(AL) or FORTRAN) • You must declare all variables that are local to the function, but you should not redeclare a variable, type, or constant with the same name as a formal parameter or the function identifier. Each function must include a statement or statements that assigns a value of the result type to the function name. The last value that is assigned to the function name is returned to the calling program unit. To use the value, include a function call in the calling unit. Unlike a procedure call, a function call is not a statement. It simply represents a value of the function's resuJt type. 6-33 PROCEDURES AND FUNC~IONS Side Effects A side effect is an assignment to a non]ocal variable, or to a VAR parameter, within a function block. Side effects can change the intended action of a program and therefore, should be avoided. The following program illustrates an example of a side effect. PROGRAM Example (OUTPUT)~ VAR X,Y : INTEGER, ANSI, ANS2 : BOOLEAN; FUNCTION Positive (ThisVar BEGIN Positive := FALSE; IF ThisVaT' :::- 0 THEN BEGIN X := ThisVar - 10; Positive := TRUE END END; (* 0~nd F'o~; i t i v(,.~*) INTEGEI:;: ) (* Side effect on X *) (* MAIN PROGRAM *) BEGIN Y ::::: ?; BOOLEAN; X: == 1 ~5 Y ANS1 != Positive(X) AND Positive(Y), WRITEI... N ('ANSI e(~uals',ANS1); Y != '7; X !:::: 1:5, ANS2 != Positive(Y) AND Positive(X); WRITELN ('ANS2 eouals',ANS2) END. This example generates the following output: ANS 1 e(~ua 1 5 ANS2 e~uals TRUE FALSE Thus, the output depends on which function call is evaluated first: PositivelY) or Positive(X). PASCAL does not guarantee which part of an expression is evaluated first. The resulting value of a function should not depend on when the function is called, as it does in the example above. Therefore, you shou]d avoid side effects on global variables. Example I FUNCTION COUPONS: REAL; VAR ANS : (YES, NO); AMOUNT, SUBT : REAL; BEGIN SUBT := 0; WRITELN ('AnY coupons? Type ~es or no.'); READLN (ANS); IF ANS==YES THEN BEGIN WRITELN ('Type value of each coupon, one per line, CTRL/Z when finished?'); REPEAT READLN (AMOUNT); SUBT := SUBT + AMOUNT UNTIL EOF END; COUPONS := SUBT END; (* End COUPONS* ) 6-34 PROCEDURES AND FUNCTIONS The function COUPONS computes the total value of a group of coupons. It uses only the three local variables, ANS, AMOUNT, and SUBT, and requires no parameters. The result of this function is the real totaJ of the coupon values. The assignment statement, COUPONS := SUBT, assigns the result to the function identifier. To use the function COUPONS, specify its name, as follows: TOTAL := SUBTOTAL - COUPONS; The function call is treated as a real-vaJued expression in this statement. Note that you can use the function call in the same way that you can use a value of its result type. Example 2 FUNCTION SYMMETRY <VAR A : ARR) : BOOLEAN; <*This function returns true if the returns false otherwise.*) VAR I, J : INTEGER; BEGIN SYMMETRY := TRUE; FOR I := 1 TO SIZE DO FOR J := I TO SIZE DO IF A[I,JJ <> A[J,IJ THEN END; <* SYMMETRY *) arra~ A is s~mmetric; it SYMMETRY:= FALSE the array A. The function SYMMETRY uses one variable parameter, if A is result is TRUE SYMMETRY returns a Boolean value; the symmetric, and FALSE if A is not symmetric. 6.6 FORWARD DECLARATIONS Normally, you must declare subprograms before you refer to them. However, a subprogram can reference another subprogram that has not yet been declared if you use a FORWARD declaration. The forward declaration provides the compiler with information about the forward-declared subprogram's formal parameters, and indicates that the block of the subprogram follows later in the source file. For example, a complete declaration is impossible if two subprograms call each other recursively. Omitting the declaration is also impossible because PASCAL needs information about a subprogram's formal parameters before it can compile a reference to the subprogram. Therefore, you must forward-declare one of the recursive subprograms. A forward declaration consists of the subprogram heading (including the formal parameter list, if any, and the result type, if it is a function) and the FORWARD directive without a subprogram block, for example: PROCEDURE CHESTNUT (BLD :REAL; DOC: CHAR; VAR ARC: REC);FORWARD; This example declares the procedure CHESTNUT in a FORWARD declaration. The FORWARD declaration includes only the information shown in the example. It could also include FORTRAN or GLOBAL, as in Format 2 above. 6-35 PROCEDURES AND FUNCTIONS When you specify the block of a forward-declared subprogram, you must not repeat the formal parameter list or the result type of a function. Except for these omissions, declare the heading and block in the normal way. Example FUNCTiON ADDER (OPi, OP2, OP3 : REAL) : REAL; FORWARD; PROCEDURE PRINfER (STUDENT: NAME_ARRAY) ; BEGIN Z := ADDER CA,B,C) END; FUNe'fION ADDER (* OPi, OP2, OP3 REAL BEGIN PRINTER ('Leonardo da Vinci'); This example forward-declares the function ADDER. The block of the function appears after the declaration of the procedure PRINTER. Note that the heading of the ADDER block specifies its formal parameters and result type within comment delimiters. Although you must omit the parameter list and result type when you define the function block, inserting them as a comment is a good documentation practice. 6.7 EXTERNAL SUBPROGRAMS The FORTRAN and EXTERNAL directives indicate procedures and functions that are defined external to a PASCAL program. With these directives, you can declare subprograms written in another language (such as FORTRAN or MACRO) and PASCAL subprograms that are compiled separately. In PASCAL, the FORTRAN directive should be used only for separately compiled routines written in FORTRAN or a language using the FORTRAN subprogram calling conventions. The EXTERNAL directive must be used only for separately compiled external routines written in PASCAL. If you declare separately compiled PASCAL subprograms as EXTERNAL, their names must be unique within the first six characters. In addition, an external subprogram cannot have the same name as the main program. 6-36 PROCEDURES AND FUNrTIONS Example 1 FUNCTION SCORE (RESULT: REAL) REAL; EXTERNALf The function SCORE is a procedure in a library that exists This declaration declares SCORE as an external subprogram. on disk. Example 2 PROCEDURE FORSTRCS : PACKED ARRAY[L •• U:INTEGERJ OF CHAR) FORTRAN; This statement declares the FORTRAN procedure FORSTR. The parameter list specifies S as a conformant-array parameter. 6.8 formal MODULES FOR SEPARATE COMPILATION By placing PASCAL procedures and functions in a MODULE, you can compile them separately from the main program. At load time, you specify the compiled files containing the main program and the modules to be loaded together in the executable image. The executable image can include any number of modules, and each module can contain any number of subprograms. Format [ [OVERLAID1] MODULE module name (program parameters); label section; constant section; type section; variable section; procedure-ana-function section; END. [OVERLAID] Specifies that the module shares global values with the main program that calls it. If the module is OVERLAID; then the constant, type, and variable sections must be identic~l to those in the main program. module name specifies the identifier to be used as the name of the module. program parameters lists the external files. This list must be identical and in content to the list in the main program heading. in order label section declares global labels. PASCAL issues a warning-level message if a module contains a label section, but ignores the labels. constant section declares global constant identifiers as in a main program. type section defines global types as in a main program. 6-37 PROCEDURES AND FUNCTIONS variable section declares global variables as in a main program. procedure-and-function section declares the procedures and functions contained in the module. A module is similar to a main program, except that it has no value initialization section and no executable section. Modules can contain the label, constant, type, variable, and procedure-and-function sections. (PASCAL issues a warning-level message if a nodule contains label declarations, but ignores the labels.) If the module is OVERLAID, then the constant, type, and variable sections and the program parameters must be identical to those in the main program. The procedure-and-function section defines the subprograms contained in the module. To ensure that the program parameters and the constant, type, and variable sections are identical in the main program and in all modules, you can place them in a separate file. Then, you can use the %INCLUDE directive to insert the contents of the file into the main program and into all modules, instead of repeating all the declarations and definitions. If a module shares global variables with a main program, both the module and the program headings must include the attribute [OVERLAID]. If the module heading does not contain [OVERLAIDl, then all its global variables are private to the module and cannot be accessed by the main program or other modules. Subprograms declared at the outermost level of a module can be declared and called from the main program (or from another module). You must declare the subprogram with the EXTERNAL modifier in the calling program unit and with the [GLOBALl attribute in the module. Similarly, subprograms declared at the outermost level of the main program with the [GLOBAL] attribute can be declared as EXTERNAL in a module. Each subprogram in the module can access data declared either to itself or by the main program. locally Examples [OVERLAID] MODULE SEP (INPUT, OUTPUT); VAR I : INTEGER; PROCEDURE READER (N : INTEGER); VAR K,P : INTEGER; BEGIN I := 0; FOR K := 1 TO N DO BEGIN READ (P); IF P=O THEN I END END; <* READER *) END. <*MODULE SEP *) := I + 1; The MODULE SEP contains one procedure, READER. You can declare READER as an external subprogram in another module or in the main program. Because SEP contains the definition of a global data item, I, it is declared as an [OVERLAID] module. If you declare READER as an external subprogram, you must declare READER as [GLOBAL] in the module so that the main program can call it. 6-38 CHAPTER 7 INPUT AND OUTPUT This chapter describes input and output (I/O) for PASCAL on TOPS-20. PASCAL provides predefined procedures to perform input and output to file variables. These procedures are divided into the following categories: General Procedures • OPEN -- associates • CLOSE -- closes a file • FIND -- performs direct access to file components R file with specified characteristics Input Procedures • RESET -- opens a fiJe and prepares it for input • GET -- reads a file component into the file buffer variable • READ -- reads a file component into • READLN -- reads a line from a text file R specified variable Output Procedures • REWRITE -- truncates a file to length zero for output • PUT -- writes the contents of the file buffer the specified file • WRITE -- writes specified values into a file • WRITELN -- writes a line into a text file • LINELIMIT -- terminates program execution after a number of lines have been written into a text file • PAGE -- skips to the next page of a text file In addition, you can use the predefined functions EOF text files. The following sections describe: • PASCAL file characteristics • PASCAL record formats 7-1 and prepares variable and it into specified EOLN with INPUT AND OUTPUT • PASCAL input and output procedures • Terminal 1/0 The input and output procedures are 7.1 presente~ in alphabetical order. FILE CHARACTERISTICS This section describes the organization accessing records. of records and methods of The term file organization app] ies to the way records are physically arranged on a storage device. The term record cccess refers to the method used to read records from or write records to a file, regardless of the file's organization. A file's organization is specified when the file is created and cannot be changed. Record access is specified each time the file is opened and can vary. 7.1.1 File Names The file name indicates the system name of a file that is represented by a PASCAL file variable in an OPEN procedure (Section 7.7). For the file name, you can specify a character-string expression that contains a TOPS-20 file specification or a logical name. Apostrophes are required to delimit a character-string constant or a logical name used as a file name. 7.1.2 Logical Names The TOPS-20 operating system provides the logical name mechanism as a way of making programs device and file independent. If you use logical names, your PASCAL program need not specify the particular device on which a file resides or the particular file that contains data. Specific devices and files can be defined at run time. A logical name is an alphanumeric string that you specify in place of a file specification. Logical names provide great flexibility because they can be associated not only with. a complete file specification, but also with a device, a device and a directory, or even another logical name. On TOPS-20 you can create a logical name specification by means of the TOPS-20 program execution, you can associate the with the file specifications appropriate @DEFINE DATA: and associate it with a file DEFINE command. Thus, before logical names in your program to your needs, for example: PS:<BENJAMIN)TEST.DAT.2 This command creates the logical names DATA: and associates it with the file specification PS:<BENJAMIN)TEST.DAT.2. The system uses this file specification when it encounters the logical name DATA: during program execution, for example: OPEN (INDATA, 'DATA:', OLD); 7-2 INPUT AND OUTPUT In executing this PASCAL statement, the system uses the file specification PS:<BENJAMIN>TEST.DAT.2 for the logical name DATA:. To specify a different file when you execute the program again, issue another DEFINE command, for example: @DEFINE DATA: PS:<JENNIFER)REAl.DAT+7 This command associates the logical name DATA: with a different file specification and replaces the previous logical name assignment. The OPEN statement above now refers to the file PS:<JENNIFER>REAL.DAT.7. For more inform3tion about the use of logical names, refer to the TOPS-20 User's Guide. 7.1.3 File Organization PASCAL supports sequential file organization. Sequential files consist of records arranged in the order in which they are written to the file. The first record written is the first record in the file; the second record written is the second record in the file, and so on. As a result, records can be added only at the end of the file. 7.1.4 Record Access You specify record access mode as a parameter to the PASCAL provides two ways of accessing records: • Sequential • Direct OPEN procedure. If you select sequential access mode, records are written to or read from the file, starting at the beginning and continuing through the file one record after another. Having sequential access to a file means that you can read a particular record only after reading all the records preceding it. New records can be written only at the end of a file that is open for sequential access. If you select direct access mode, you can specify the order in which records are accessed. Each FIND procedure call must include the relative record number indicating the record to be read. You can directly access a file only if it contains fixed-length records, resides on disk, and is open for input (reading). 7.2 RECORD FORMATS Records are stored in one of two formats: • Fixed length • Variable length You can access fixed-length records in either sequential or direct mode. Variable-length records can be accessed only in sequential mode. 7-3 I~PUT 7.2.1 AND OUTPUT Fixed-Length Records When you specify fixed-length records, you ~re specifying that all records in the file contain the same number of bytes. A file opened for direct access must cont3in fixed-length records to allow the record location to be computed correctly. All binary files (that is, all files except TEXT files) must have fixed-length records. P~SCAL does not support binary files with variable-length records. 7.2.2 Variable-Length Records Variable-length records can contain any nUffiber of byt~s up to the buffer size specified when the file was opened. TEXT files must have variable-length records. PASCAL does not support TEXT files with fixed-length rec~rds. 7.3 THE CLOSE PROCEDURE The CLOSE procedure closes an open file. Fo rma t. CLOSE (file variable); where: file variable specifies the file to be closed. Execut.ion of this procedure causes the system to close t.he file. Each file is automatically closed upon exit from the procedure in which it is declared, except those which have been dynamically allocated with the procedure NEW. These files should be explicitly closed; if not, they are automatically closed when the program ends, or when they are DISPOSED. You can close only files that have been opened explicitly with the OPEN procedure or implicitly by the RESET or REWRITE procedure. Therefore, you cannot close the predeclared file variables INPUT and OUTPUT. Example CLOSE (AlbulTls); This procedure closes the file Albums to further access, the file if it is internal to the current program. 7.4 and deletes THE FIND PROCEDURE The FIND procedure positions a file pointer at a in the file. Fo rma t FIND (file variable, integer expression); 7-4 specified component INPUT AND OUTPUT where: file variable specifies a file that is open for direct access. The file must have fixed-length records. integer expression specifies the positive integer expression indicating the component at which to position the file. The component number must not be less than or equal to zero. The FIND procedure allows you to directly access the components of a file. You can use the FIND procedure to move forward or backward in a file. The file must be open for direct access. That is, you must have specified DIRECT in the OPEN statement for that file. In addition, the file must have fixed-length records. After execution of the FIND procedure, the file is positioned at the specified component. The file buffer variable assumes the value of the component, for example: FIN D (A 1 b 1.1 III S, 4) ~ As the result of this statement, the file position moves to the fourth component in the file Albums. The file buffer variable Albumsassumes the value of the fourth component. If you specify a component beyond occurs. the end of the file, no error You can use the FIND procedure only when reading a file. If the file is open for output (that is, with REWRITE), a call to FIND results in a run-time error. Example I BEGIN FIND (Albums, Current + 2); END; If the value of Current is 6, this statement causes the file position to move to the eighth component. The file buffer variable Albumsassumes the value of the component. Example 2 BEGIN FIN D (A 1 b U IT! S, C U l'r e n t . - 1 ) ; END~ If the value of Current is 6, this statement causes the file to move backward one component to the fifth component. 7-5 position INPUT AND OUTPUT 7.5 THE GET PROCEDURE The GET procedure reads the next component of a buffer variable. file into the file Fo rma t GET (file variab1e); where: file variable specifies the file to be read. Before you use the GET procedure to read one or more file components, you must have called the RESET procedure to prepare the file for reading (input). RESET moves the file position to the first component and assigns its value to the file buffer variable. As a result of the GET procedure, the file position moves to the next component of the file. The file buffer variable takes on the value of that component, for example: r;: [ ~:) E T (B () 0 k ~:; ) Y N P ItJ Y' pc: ::" li n 0 k ~:; ,., Y GET (Buoks); After execution of the RESET procedure, the file buffer variable Books is set to the first component of the file. The assignment statement assigns this value to the variable Newrec. The GET proce~ure then assigns the value of the second component to Books moving the file position to the second component. The next GET procedure moves the file position to the third component, as shown in Figure 7-1. A A , RESET GET (BOOKS) (BOOKS) B.,'""'", of File CT I . .I EOF • • t I RESET GET GET (BOOKS) (BOOKS) (BOOKS) FigurE~ 7-1: MR-S-3117-83 File position After GET By repeatedly using GET statements, you can read sequentially the file. 7-f) through INPUT AND OUTPUT When you reach the end of the file and you request a GET operation, EOF automatically becomes TRUE, and the file buffer variable becomes undefined. When EOF is TRUE, you cannot use the GET procedure. P~SCAL signals a run-time error, and program execution is aborted. Example BEGIN GET (Phones); END; This example reads the next component of the file Phones into the file buffer variable Phones EOF(Phones) must be FALSE; if it is TRUE, an error occurs. A • 7.6 THE LINELIMIT PROCEDURE The LINELIMIT procedure terminates execution of the program after specified number of lines have been written into a text file. a Format LINELIMIT (file variable, n); where: file variable specifies the text file to which applies. n represents a positive integer expression indicating the number of lines that can be before execution the file written to terminates. this limit When PASCAL initializes a text file, it specifies a large default line limit. You can override this limit by calling LINELIMIT with your desired value. After the number of lines output to the limit, program execution terminates. file has reached the line Example BEGIN LINELIMIT (Debts,100); Execution of the program terminates after 100 lines have been into the text file Debts. 7-7 written INPUT AND OUTPUT 7.7 THE OPEN PROCEDURE The OPEN procedure does not actually open a file but rather allows you to specify file attributes. You cannot use OPEN on a file th~t has had a RESET or REWRITE done, or on the predeclared file INPUT. Fo rma t 1 OPEN (file variable [ ,file name E [,history E IT ,record length E [,record-access-method E [ ,record type E [,carriage control E ); Format 2 OPEN (FILE VARIABLE := file variable [ ,FILE NAME := file name E [ ,HISTORY := history status E [ ,RECORD LENGTH := positive integer E [ ,RECORD-ACCESS METHOD := record-access-mode [ ,RECORD-TYPE :~ record type E [ CARRIAGE CONTROL .= carriage control D ); E where: file variabJe specifies the PASCAL file variable associated with the file. You cannot open the predeclared file variable INPUT. (internal files) This parameter is ignored for internal files. The system creates a unique name for each internal file. (external files) file name provides information about the file to TOPS-20. The file name can be a variable or constant identifier defined as type PACKED ARRAY (l .• n] OF CHAR, or a file specification enclosed in apostrophes (for example, 'PS:(MASELLA)BOOKS.DAT') . If you omit the file name, PASCAL will first attempt to use the file variable identifier as a logical name. If that name is not defined, PASCAL will use the defaults shown in Table 7-1. The file variable and the file name parameters designate the file to be opened. The remaining parameters specify attributes for the file and are summarized in Table 7-2, in Section 7.7.5. Except for the file variable name, all parameters are optional. Any parameters you specify, however, must be in the order shown above unless you use keywo rd syn tax. You can specify either the value of the parameter or the keyword the value of the parameter. You can also use a combination. 7-8 and INPUT AND OUTPUT To specify only the value without the keyword, place each parameter in the same order shown in the format. If a particular parameter is not used, then a comma may be inserted. PASCAL generates a warning message if the position of an unused parameter is not jndicated by a comma. However, the correct default for the missing parameter is used in either case. To use a keyword, specify the keyword and its associated value. When you use a keyword, you have to specify only the parameters that are used; it is not necessary to insert ~ comma to indicate unused parameters. Keyword parameters can be placed in any order; they do not have to be in the same order as shown in the format. You can also use a combination of values and keywords with values. However, once you use a keyword within the statement, subsequent values must be associated with a keyword. Table 7-1: Default Values for TOPS-20 External File Specifications -----------------------------------------------------------------------------------Element Default Device Current user device Directory Current user directory File name PASCAL file variable first truncated to characters File type DAT Generation number OLD: highest current number NEW: highest current number + 1 --------------------------- name, 39 Because the RESET and REWRITE procedures actually open files, you need not always use the OPEN procedure. RESET and REWRITE impose the defaults for the TOPS-20 file specification, file status, record length, record access mode, record type, and carriage control shown in Table 7-1 and Table 7-2. For the file status attribute, RESET uses a default of OLD, and REWRITE uses a default of NEW. You must use the OPEN procedure for the following: • To open a file for DIRECT access by the FIND procedure • To specify a buffer size other than 133 for a text file • To open any file with other than the default file name 7-9 INPUT AND OUTPUT 7.7.1 File History -- NEW, OLD, READONLY, or UNKNOWN The file status indicates whether the specified file exists or must be created. The possible values are: NEW OLD HEADONLY UNKNOWN A file status of NEW indicates that a new file must be the specified attributes. NEW is the default value. created with If you specify OLD, the system tries to open an existing file. An error occurs if the file cannot be found. OLD is invalid for internal files, which are newly created each time the declaring program or subprogram is executed. A file status of READONLY indicates that an existing file is being opened only for reading. An error occurs if you try to write to a file that has been opened with READONLY. If you specify UNKNOWN, the system first tries to open an existing file. If an existing file cannot be found, a new file is created with the specified attributes. If you specify READONLY, the system generates an error if a REWRITE is performed on the file. READONLY implies OLD. 7.7.2 Record Length The record length parameter specifies the record length file. Any positive integer can be used. used in the The record access mode specifies the access to the components file. The modes are: of the In SEQUENTIAL mode, you can access files with fixedvariable-length records. The default access mode is SEQUENTIAL. or 7.7.3 Record Access Mode -- SEQUENTIAL or DIRECT DIRECT SEQUENTIAL DIRECT mode allows you to use the FIND procedure to access files with fixed-length records. You cannot access a file with variable-length records in DIRECT mode. 7-10 INPUT AND OUTPUT 7.7.4 Record Type -- FIXED or VARIABLE The record type specifies the structure of the records in a file. record types are: The FIXED VARIABLE A value of FIXED indicates that all records in the file have the same length. A value of VARIABLE indicates that the records in the file can vary in length. FIXED is the default for non-TEXT files; VARIABLE is the default for TEXT files. 7.7.5 Carriage Control -_. LIST, CARRIAGE, or NOCARRIAGE The carriage control option specifies the carriage control format a text file. The options are: for LIST CARRIAGE FORTRAN NOCARRIAGE NONE A value of LIST indicates single spacing between components. LIST is the default for all text files, including the predefined file OUTPUT. The CARRIAGE option indicates that the first character of every output line is a carriage control character. These characters and their effects are summarized in Table 7-4. FORTRAN is equivalent to CARRIAGE. NOCARRIAGE means that no carriage control applies to the file. In particular, WRITELN will not output an EOLN to a NOCARRIAGE file, and the PAGE procedure will cause a run-time error. NONE is equivalent to NOCARRIAGE. 7-11 INPUT AND OUTPUT Table 7-2 summarizes the file attributes. Table 7-2: Summary of File Attributes Parameter possible Values File status OLD, NEW, UNKNOWN Reco rd I eng th any positive integer 133 Record-access mode DIRECT or SEQUENTIAL SEQUENTIAL Record type FIXED or VARIABLE VARIABLE for files; FIXED no n- t ext f i 1 e s . Carriage control LIST, FORTRAN, or NONE LIST for all text files; NOCARRIAGE for all other files 7.7.6 RE~DONLY Default or CARR Lh.G E , NOCARRIAGE, NEW text for Examples Example I TEXT; BEGIN OPEN (Userguide); EN1H In this example, the OPEN procedure specifies only the file variable so no defaults for the file will be changed. This usage of OPEN essentially causes no action. Example 2 BEGIN OPEN (Userguide",80); END; The OPEN statement characters. sets the record Exampl e 3 BEGIN OPEN (OUTPUT"""CARRIAGE); END; 7-12 length for USERGUIDE to 80 INPUT AND OUTPUT This example causes the system to interpret the first character of each line written to the predeclared file OUTPUT as a carriage control character. When you call OPEN for the predeclared file OUTPUT, you can specify only a carriage control option. If you include any other parameters, an error occurs. Example 4 BEGIN [) PEN (A :I. b I..Im S 9 ,. P!:l : -::: ,J ENNJ F Er~ :> I NVENT I, 0 L.. D, , [I IRE CT ) ; END, The file variable albums will be associated with the file specification PS:(JENNIFER>INVENT. A RESET will initiate reading of the existing (OLD) file, or cause an error if the file does not exist. The file wil] be opened for direct access; that is you Cr.ln use the FIND procedure with this file. A REWRITE will ignore the OLD parameter. Example 5 BEGIN OPEN (~;DlaT" 'Enpr'~J~:l:" NEWl' , FIXED); END; Assuming that Energy is defined as a logical name, this statement causes a RESET or REWRITE to create a file with the specification designated by the logical name Energy. The identifier Solar is used within the program to refer to the TOPS-20 logical name. The file is created with fixed-length records. Default values are used for the record length and the record access parameters. Exampl e 6 BEGIN OPEN (File_Name := 'PS:-:::SMITH:>PLAN.DAT',RECORD_TYPE != VARIABLE, File_Variable:=Plans); END, The file variable plans is associated with the file PLAN.DAT on PS: with a directory of <SMITH>. The file name and record type parameters use keywords. Because the file name keyword is used, each subsequent parameter must use a keyword. It is not necessary to indicate each unused parameter with a comma when keywords are used. 7-.13 INPUT AND OUTPUT 7.8 THE PAGE PROCEDURE The PAGE procedure skips to the next page of a text file. Fo rma t P i'\G E (f i 1 e va ria b] e) ; where: file variable specifies a text file. Execution of the PAGE procedure causes the system to flush the contents of the record huffer, then skip to the next page of the specified text file. The next 1 ine written to the file begins on the first line of a new page. You can use this procedure only on text files. If you specify a file of any other type, PASCAL issues an error message. The value of the page eject record that is output to the file depends on the carriage control format for that file. When CARRIAGE is enabled, the page eject record is equivalent to the carriage control character '1'. When LIST is enabled, the page eject record is a form feed character. When NOCARRIAGE is enabled, the PAGE procedure generates an error. Example 1 BEGIN PAGE (Use T'~.:.lU i. de) ; END; This example causes a page eject record to be written in the text file Userguide. Example 2 BEGIN PAGE (OUTPUT); ENIH This example calls the PAGE procedure for the predeclared file OUTPUT. As a result of this procedure, a page eject record is output at the terminal (in interactive mode) or in the batch log file (in batch mode) • 7-14 INPUT AND OUTPUT 7.9 THE PUT PROCEDURE The PUT procedure appends a new component to the end of a file. Fo rma t PUT (file va:riable); where: file variable specifies the file to which components will be written. one or more Before executing the PUT procedure, you must have executed the REWRITE procedure. REWRITE clears the file and sets EOF to TRUE, preparing the file for output. If EOF is FALSE, the PUT procedure fails; a run-time error occurs; and program execution is terminated. The PUT procedure writes the value of the file buffer variable at the end of the specified file. After execution of the PUT procedure, the value of the file buffer variable becomes undefined. EOF remains TRUE. Example PROGRAM Bookfile (INPUT,OUTPUT,Books); TYPE St T':i n~~~ :::: PACKED ARRAY [1 •• 40 J OF CHAR; Book rec ::!: RECORD Author : Strins; Title : Strins END; VAR Newbook: Bookrec; Books : FILE OF Bookrec; N : INTEGER; BEGIN F~EWR I TE (Books); FOR N !: 1 TO 10 DO BEGIN WITH Newbook DO BEGIN WRITE ('Title:'); f~EAD (Title); WRITE ('Author!'); READ (Author); END; Books- != Newbook; PUT (Book~;) END END. This program writes the first 10 records into the file Books. The records are input from the terminal to the record variable Newbook. They consist of two 40-character strings denoting a book's author and title. The FOR loop accepts 10 values for Newbook, assigning each new record to the file buffer variable BooksA. The PUT statement writes A the value of Books into the file for each of the 10 records input. 7-15 INPUT AND OUTPUT 7.10 THE READ PROCEDURE The READ procedure reads one or more file components into of the component type. a variable Format READ ( [file variable,TI variable name [,variable name •.. TI); where: file variable specifies the input file. If you omit the file variable, PASCAL uses INPUT by default. variable name specifies the variable into which the file component(s) are read. For a text file, many file components can be read into one variable. By definition, the READ procedure for a nontext file performs an assignment statement and a GET procedure for each variable name. Thus, the procedure call READ (file variable, variable name); is equivalent to variable name := file GET (file variable); variable~; The READ procedure reads from the file until it has found a value for each variable in the list. The first value read is assigned to the first variable in the list; the second value is assigned to the second variable, and so on. The values and the variables must be of compatible types. For a text file, more than one file component (that is, more than one character) can be read into a single variable. For example, many text file components can be read into a string or numeric variable. The READ procedure repeats the assignment and GET process until it has read a sequence of characters that represent a value for the next variable in the parameter list. It continues to read components from the file until it has assigned a value to each variable in the list. Values from a text file can be read into variables of integer, real, character, string, and enumerated types. In the file, values to be read into integer and real variables must be separated by spaces or must be put on new lines. Values to be read into character variables, however, must not be separated because they are read literally, character-by-character. Constants of enumerated types must be separated by at least one space. Any other character that is invalid in an identifier terminates the constant. Only the first 31 characters of the constant are significant; PASCAL ignores any remaining characters. You can use READ to read a sequence of characters from a text file into a string (that is,a variable of type PACKED ARRAY[l •• n] OF CHAR). PASCAL assigns successive characters from the file to elements of the array, in order, until each element has been assigned a value. If any characters remain on the line after the array is full, the next READ begins with the next character on that line. If the end of the line is encountered before the array is full, the remaining elements are assigned spaces. 7-16 INPUT AND OUTPUT READ does not read past EOLN if it is reading into a string type. Instead, READ continues to return blanks until the EOLN is explicitly passed by using READLN. If you call READ when the file is positioned at the end of a line, the file position moves to the beginning of the next line, unless it is c. string variable. Characters are then read into the specified starting variable. If this line is empty, the string is filled with spaces. Every text file ends with an end-of-line mark and an end-of-file mark. Therefore, the function EOF never becomes TRUE when you are reading strings with the READ procedure. To test EOF when reading strings, use the READLN procedure. Example I BEGIN READ (TemFY Ase~ Weisht); END; Assume that Temp, Age, and Weight are real variables, and you type the following values: 90.6 11.0 in 7~5+0 The variable Temp takes on the value 98.6; Age takes on the value 11.0; and Weight takes on the value 75.0. Note that you need not type all three values on the same line. Example 2 TYPE Strins VAR Names Pres~ = PACKED ARRAY [1 •• 20J OF CHAR; TEXT; Veep: Strins; BEGIN READ (Name!:., Pres, Veep); This program fragment declares and contains the following characters: John F. Kennedy Hubert H. Humphrey Richard M. Nixon reads Lyndon B. Johnson <EOLN) Spiro T. Agnew the file Names, which Lyndon B. Johnson <EOLN) <EOLN) The first call to the READ procedure sets Pres equal to the 20-character string 'John F. Kennedy 'and Veep equal to 'Lyndon B. Johnson The second call to the procedure assigns 'Lyndon B. Johnson to Pres and spaces to Veep. Unless READLN is used to read past the EOLN, READ continues to assign spaces. 7-17 INPUT AND OUTPUT THE READLN PROCEDURE 7.11 The READLN procedure reads lines of data from a text file. Fo rma t READLN [( [file variable,E variable name [,variable name···E )E where: file variable specifies the name of the text file to be read. If you do not specify a file variable, PASCAL uses INPUT by default. variable name specifies the variable into which a value will be read. If you do not specify any variable names, READLN skips a line in the specified file. The READLN procedure reads values from a text file. After reading values for all the listed variables, the READLN procedure skips over any characters remaining on the current line and positions the file at the beginning of the next line. All the values need not be on a single line; READLN continues until values have been assigned to all the specified variables, even if this process results in the reading of several lines of the input file. READLN performs the following sequence: READ (file variable, variable name .•. ); READLN (file variable); EOLN(file variable) is TRUE only if the new line is empty. You can use the READLN procedure to read integers, real numbers, characters, strings, and constants of enumerated types. The values in the file must be separated as they are for the READ procedure. The READLN statement automatically pads strings. Thus, it is not necessary to pad strings with spaces to match the variable size if you are using the predefined file INPUT or reading from a file defined as TEXT. If EOLN() is TRUE when you call READLN, the first value read is the first value in the next line, unless you are reading a character. If you are reading a character, the first value read is a space. Example TYPE Strin~ = PACKED ARRAY [1 •• 20J OF CHAR; VAR Names : TEXT; Pres, Veep : Strin~; WHILE NOT EOF (Names) DO; BEGIN READLN (Names, Pres, Veep); END; 7-18 INPUT AND OUTPUT This program fragment declares and contains the following characters: John F. Kennedy Hubert H. Humphrey Richard M. Nixon (EOLN> (EOF> reads Lyndon B. Johnson (EOLN> ~;piro T. Agnew the Lyn~on file Names, which B. Johnson (EOLN> (EOLN> The READLN procedure reads the values 'John F. Kennedy for Pres and 'Lyndon B. Johnson ' f o r Veep. It then skips to the next line, ignoring the remaining characters on the first line. Subsequent execution of the procedure assigns the value 'Hubert H. Humphrey , to Pres and sets Veep to all blanks, because READ of a string will not go past EOLN. The next execution of the procedure assigns the value 'Richard M. Nixon ' to Pres and 'Spiro T. Agnew to Veep, then skips to the next line. The last execution of READLN sets both Pres and Veep to all blanks, and skips the EOLN, which causes EOF to become TRUE, so the loop exits. 7.12 THE RESET PROCEDURE The RESET procedure readies a file for reading by pointer to the first component in the input file. setting the file Format RESET (file variable); where: file variable specifies the file to be read. If the file is not already open, RESET opens it using the defaults listed in Table 7-1 and Table 7-2. To open a file that does not use default values, use the OPEN statement. After execution of RESET, the file is positioned at the first component; and the file buffer variable contains the value of this component. The arrow in Figure 7-2 shows the file position after RESET. If the file is empty, EOF is TRUE; otherwise, EOF is FALSE. If the file does not exist, RESET returns an error at run time; RESET does not create the file. Figure 7-2: File position after RESET 7-19 INPUT AND OUTPUT You must call RESET before reading any file except the predeclared file INPUT. If you call RESET for the predeclared file INPUT or OUTPUT, a run-time error occurs. Examples Example I BEGIN OPEN (Phones,'Phones.Dat'"DIRECT); RESET (Phones); These statements open the file variable Phones for direct access on input. After execution of the OPEN and RESET procedures, you can use the FIND procedure for direct access to the components of the file Phones. Example 2 BEGIN RESET (Weights)~ END~ If the file variable Weights is already open, this statement enables reading and sets Weights to the first file component. If the fil~ is not open, this statement causes the system to search for the file designated by the logical name Weights: If no such logical name is assigned, the system searches for the file WEIGHTS.DAT on the user's default device and directory. If the file exists it is opened for sequential read access. If the file does not exist, a run-time error occurs. A 7.13 THE REWRITE PROCEDURE The REWRITE procedure readies a file for output by pointer to the first component of the output file. setting the file Format REWRITE (file variable); where: file variable specifies the file to be enabled for output. If the file does not exist, REWRITE creates and opens it using the defaults listed in Table 7-1 and Table 7-2. If the file exists, REWRITE supersedes it using the defaults listed in Table 7-1 and Table 7-2. To open a file that does not use default values, use the OPEN statement. 7-20 INPUT AND OUTPUT You must call REWRITE before writing any file except the predeclared file OUTPUT. If you call REWRITE for the predeclared file INPUT or OUTPUT, a run-time error occurs. The REWRITE procedure sets the file to length zero and sets EOF to TRUE. You can then write new components into the file with the PUT, WRITE, or WRITELN procedure (WRITELN is defined only for text files). After the file is open, successive calls to REWRITE close and supersede the existing file; that is, they create new versions of the file. To update an existing file, you must copy its contents to another file, specifying new values for the components that you need to upda te. Example I BEGIN REWRITE (Storffis)~ END; If the file variable Storms is already open, this statement enables writing and sets the file position to the beginning of the file. If Storms is not open, a new version is created with the same defaults as for the OPEN procedure. Example 2 BEGIN OPEN (f~t:'sult~;" 'F'~:;:<CHEN>ISSUES+DAT' , OLD" ,FIXED); REWRITE (Hesults), END, The OPEN procedure sets defaults for the file variable Results, which is associated with the file ISSUES.DAT in directory PS:<CHEN>. The REWRITE procedure discards the current contents of the file Results and sets the file position at the beginning of the file. After execution of this statement, EOF(Results) is TRUE. 7.14 THE WRITE PROCEDURE The WRITE procedure writes data into a file. Fo rma t WRITE [ file variable,] print l i s t ) ; 7-21 INPUT AND OUTPUT where: file variable specifies the file to be written. If you omit the file variable, PASCAL uses OUTPUT by defaul t. print list specifies the values to be output, separated by commas. The print list can contain constants, variables, and expressions. For nontext files, the items in the print list must be compatible with the file component type. By definition, the WRITE procedure for a nontext file performs an assignment statement and a PUT procedure for each variable name. Thus, the following procedure calls are equivalent: 1. WRITE (file variable, variable name); 2. file variable := variable name; PUT (file variable) A For text files, the WRITE procedure converts each item in the print list to a sequence of characters. The WRITE procedure repeats the assignment and PUT process until all the items in the ljst have been written in the file. The print list can specify constants, variable names, array elements, and record fields, with values of any scalar type. Each value is output with a minimum field width, as specified in Table 7-3. Table 7-3: Default Values for Field Width Type of Variable Number of Characters Printed In teg er 17. Real 16 Double 24 Boolean Character 1 Enumerated 31 String Length of string You can override these defaults for a particular value by specifying a field width in the print list. The field width specifies the minimum number of characters to be output for the value. The following is the format of the field-width specification: variable name: minimum: fraction Both minimum and fraction represent positive integer expressions. The minimum indicates the minimum number of characters to be output for the value. The fraction, which is permitted only for real numbers, indicates the number of digits to the right of the decimal point. 7-22 INPUT AND OUTPUT The following rules apply to output procedures: designating field-width parameters in 1. If a real value does not have the function parameter, prints the value in floating-point format. PASCAL 2. If the print field is wider than necessary, PASCAL prints the value with the appropriate number of leading blanks. 3. If the print field is too narrow, PASCAL treats the different kinds of write parameters as follows: • Strings and nonnumeric scalar values are truncated on the right to the specified field width. • Integers and real numbers in decimal format are printed using the full number of characters needed for the value, thus overriding the field-width specification. • Real and double values in floating-point format are printed in a field of at least eight characters (for example, -l.OE+OO). All real values in either format are printed with a leading blank if they are positive and a leading minus sign if they are negative. By default, PASCAL prints real numbers in floating-point format. real number is preceded by at least one blank, for example: Each WRITE (Shoesize); If the value of following output: Shoesize is 12.5, this statement produces the field width 1.25000000EtOl To print the value in decimal format, you must specify a as in this example: WRITE (Shoeslze:5:1); The first integer indicates that a minimum of five characters will be output. The minimum includes the leading blank, the sign (if any), and the decimal point. The second integer specifies one digit to the right of the decimal point. This statement results in the following output: 12.5 If the print field is wider than necessary, PASCAL with leading blanks. prints the value If you try to print a nonnumeric value in a field that is too narrow, PASCAL truncates the value on the right to fit into the field. For integers, however, it prints the entire value without truncation. PASCAL widens the field to eight characters for real and double-precision numbers in exponential notation. It does not truncate real and double-precision numbers in decimal notation. 7-23 INPUT AND OUTPUT For a variable of an enumerated type, PASCAL prints the constant identifier denoting the variable's value. Because PASCAL ignores any characters beyond the thirty-first in an identifier, only the first 31 characters of a long identifier appear, for example: VAR Color : (Blue,Yellow,Black,Sli~htl~_Pale_Peach_Summer_Sun5et)~ BEGIN WRITE ('M~ favorite color is ',Color:35); END; When the value of Color is Yellow, the following M~ favorite color is is printed: YELLOW When the value of Color is Slightly_Pale Peach Summer_Sunset, however, the following appears: My favorite color is Although the field width specified is wide enough for all 33 characters in the identifier, PASCAL ignores the last two characters and prints two leading blanks. Note that constants of enumerated types are printed in all uppercase characters. If you open the predeclared file OUTPUT with the carriage control option LIST, PASCAL allows you to use the WRITE procedure to prompt for input at the terminal. Each time you read from INPUT, the system checks for any output in the terminal record buffer. If the buffer contains any characters, the system prints them at the terminal, but suppresses the carriage return at the end of the lin(~. The output text appears as a prompt, and you can type your input on the same line, for example: WRITE ('Name three presidents:'); READ (Pres1, Pres2, Pres3); When PASCAL executes the READ procedure, it finds the output string waiting to be printed. PASCAL prints the prompt at the terminal, leaving the carriage just after the colon (:). You can then begin typing input on the same line as the prompt. Prompting works only for the predeclared files INPUT and OUTPUT. For any other files, no output is written until you fill the record buffer or start a new line. Example 1 = TYPE Strins PACKED ARRAY [1 •• 20] OF CHAR; VAR Names: FILE OF Strins; Pres String; BEGIN WRITE (Names, 'Millard Fillmore " Pres); END; 7-24 INPUT AND OUTPUT This example writes two components in the file Names. the 20-character string constant 'Millard FiJlmore is the string variable Pres. The first is The second Example 2 BEGIN WRITE (Num1:S:1,' and',Num2:S:1,' sum to',(NumltNum2)!6:1); END; If you specify an expression, PASCAL prints its value. For example, if Numl equals 71.1 and Num2 equals 29.9, this statement prints: 71.1 and 29.9 sum to 101.0 Note that each of the real numbers is preceded by a space. Example 3 VAR Rainamts : FILE OF REAL; Avgrain,Maxrain~Minrain : REAL; BEGIN WRITE (Rainamts,Avgrain,Minrain,0.312,Maxrain); END; The file Rainamts contains real numbers indicating amounts of rainfall. The WRITE procedure writes the values of the variables Avgrain and Minrain into the file, followed by the real constant 0.312 and the value of the variable Maxrain. 7.15 THE WRITELN PROCEDURE The WRITELN procedure writes a line of data in a text file. Format WRITELN [ file variable,] print list); where: file variable If specifies the text file to be written. you omit the file variable, PASCAL uses OUTPUT by default. print list specifies the values to be output, separated by commas. The print list can specify constants, variable names, array elements, and record fields, with values of any scalar type. Output of strings is also permitted. Each value is output with a minimum field width. 7-25 INPUT AND OUTPUT The WRITELN procedure writes the specified values into the text then starts a new line, for example: WF. : I T E t.. N (U ~:; E' T' ~.11..1 ide, / T his 11. a n 1..1 aId f.~ seT' i b c·~ s As a result of this statement, the system writes text file Userguide and skips to the next line. how Y () 1..1 the file, i n t e T' act / ) , string in the When you open a text file, you can specify the CARRIAGE option for carriage-control format. If you select CARRIAGE format, the first character of each output line IS treated as a carriage-control character when output is directed to carriage-control devices such as the terminal and the line printer. If output is not directed to a carriage-control device, the carriage-control character is written into the file and will be read when you open the file for input. Table 7-4 summarizes the carriage-control characters and their effects. For carriage-control purposes, any characters other than those in the table are ignored. listed The carriage-control character must be the first item in the WRITELN print list. For example, if the text file Tree is open with the CARRIAGE option, you can use the following statement: lAHnTEl..N (TT'ef:~' I I ~ StT'i.n~H, Strins2) ; The first item in the print list is a space character. The space indicates that the values of Stringl and String2 are printed beginning on a new line when the file is output to a terminal, line printer, or similar carriage-control device. Table 7-4: Carriage-Control Characters Character Meaning '+' Overprinting: starts output at the beginning of current line the space Single spacing: starts output at the next line of '0' Double spacing: skips a line before starting output 1' Paging: starts output at the top of a new page the beginning If you specify CARRIAGE but use an invalid carriage-control character, the first character in the line is ignored. The output appears with the first character truncated. 7-2() INPUT l\ND OUTPUT Example 1 BEGIN WRITELN (Class[lJ:2,' is the ~rade for this student.'); END; This example writes an element of the character array Class to the file OUTPUT. The value is written with a minimum field width of ~. Example 2 BEDIN WF~ I TELN; If you specify WRITELN without a file variable or print list, PASCAL ends the printing of the current line on the standard output device (usually the terminal). Example 3 TYPE String: PACKED ARRAY [1 •• 40] OF CHAR; VAR Newhires: TEXT, N : INTEGER: NE.'w T'f?C : RECORD ID : INTEGER, Name : St T' i n~H Address : String; Salary : String END, BEGIN OPEN (Newhires, CARRIAGE); WITH Newrec DO BEGIN WRITELN (Newhires, 'lNew hire t',ID,'IS ',Name); WRITELN (Newhires, , " Name, 't Lives at:'); WRITELN (Newhires); WRITELN (Newhires, , " Address) END; END; This example writes four lines in the text file Newhires. The output starts at the top of a new page, and fits the following format: New hire t 73 is Irving Washington IrVing Washington lives at: 22 Chestnut St, Seattle, Wash. 7-27 INPUT AND OUTPUT 7.16 TERMINAL I/O The PASCAL language requires that the file buffer always contain the next file component that will be processed by the program. This requirement can cause problems when the input to the program depends on the output most recently generated. To alleviate such problems in the processing of the predeclared text files INPUT and OUTPUT, PASCAL uses a technique called delayed device access, also know as lazy lookahead. As a result of delayed device access, an item of data is not retrieved from a physical file device and inserted in the file buffer until the program is ready to process it. The file buffer is filled when the program makes the next reference to the file. A reference to the file consists of any use of the file buffer variable, including its implicit use in the GET, READ, and READLN procedures, or any test for the status of the fi1e, namely, the EOF and EOLN functions. The RESET procedure initiates the process of delayed device access. RESET is done automatically on the prede~lared file INPUT. RESET expects to fill the file buffer with the first component of the file. However, because of delayed device access, an item of data is not supplied from the input device to fill the file buffer until the next reference to the file. When writing a program for which the input will be supplied by the predeclared text file INPUT, you should be aware that delayed device access occurs. Because RESET initiates delated device access, and because EOF and EOLN cause the buffer to be filled, you should place the first prompt for input before any tests for EOF or EOLN. The information you enter in response to the prompt supplies the data that is retained by the file device until you make another reference to the input file. Example VAR I INTEGER; BEGIN WRITE ('Enter an integer or an empty line: '); WHILE NOT EOLN DO BEGIN READLN (I); WRITELN ('The integer was: ' , 1:1); WRITE ('Enter an integer or an empty line: '); END; WRITELN ('Done'); END. 7-28 INPUT AND OUTPUT The first reference to the file INPUT is the EOLN test in the WHILE statement. When the test is perfor~ed, the system attempts to read a line of input from the text file. Therefore, it is very important to prompt for the integer or empty line before testing for ROLN. Suppose you respond to the first prompt by supplying an integer as input. Access to the input device is delayed until the EOLN function makes the first reference to the file INPUT. The EOLN function causes a line of text to be read into the internal line buffer. The subsequent READLN procedure reads the input value from the line of text 8nd assigns it to the variable I. The WRITELN procedure writes the input value to the text file OUTPUT. The final statement in the WHILE loop is the request for another input value. The loop terminates when the EOLN detects the end-of-line marker. 7-29 CHAPTER 8 USING PASCAL ON TOPS-20 This chapter describes how you use PASCAL with the TOPS-20 operating system. The steps in the program development process include: • Creating the source program • Compiling the program • Loading the program • Executing the program This chapter describes the standard TOPS-20 file specifications and defaults, and contains instructions for creating, compjling, loading, and executing a PASCAL program. 8.1 PROGRAM DEVELOPMENT PROCESS The TOPS-20 operating system provides a variety of methods to an executable program. produce The first step is to create described in Section 8.3. This a program using The second step is to compile the program using This is described in Section 8.4. an the editor. PASCAL is command. The third step is to load the program into memory using either the LOAD command or the LINK program. The LOAD command is described in Section 8.5. For more information about LINK, refer to the LINK Reference Manual. At this point you can use the START or the SAVE command. START runs the program that is currently loaded in memory. SAVE creates an executable image, an EXE file, and stores it in your disk area. If you use the SAVE command, you can then use the RUN command to execute the program now or at a later date. If you do not SAVE the EXE file, you must load the before you can run it. file into memory To save time, you can use the EXECUTE command. (See Section 8.6.) With EXECUTE, you can compile, load, and start a program all at once. EXECUTE does not create an EXE file. 8-1 USING PASCAL ON TOPS-20 8.2 FILE SPECIFICATIONS AND DEFAULTS A file specification indicates the input file to be processed or the output file to be produced. File specifications have the following form: device:<directory>filename.fiJetype.gen The punctuation marks required syntax that specification. (colons, separate angle brackets, and periods) are the various compone~ts of the file device identifies the device or file structure stored or is to be written. on which the file is directory identifies the name of the directory under which the file is catalogued, on the device specified. You can delimit the directory name with angle brackets, as shown above. filename identifies the file by its name. to 39 alphanumeric characters. characters. The source file name can be up REL file names can be up to six filetype describes the kind of data in the file. The source file type can be up to 39 alphanumeric characters. REL ffle types can be up to three characters. gen specifies the generation of the TOPS-20 file desired. Generations are identified by a decimal number, which is incremented by 1 each time a new generation of a file is created. A period is used to separate file type and generation. You need not explicitly state all elements of a file specification each time you compile, load, or execute a program. Only the file name is required, as long as you use the default file type. Table 8-1 summarizes the default values. 8-2 USING PASCAL ON TOPS-20 Table 8-1: File Specification Defaults Optional Element Default Value device User's current default device (DSK:) directory User's current default directory file type Depends on usage: Input to PASCAL compiler - PAS Output from PASCAL compiler - REL Input to LINK - REL Output from SAVE command - EXE Input to RUN command - EXE Compiler source listing - LST LINK map listing - MAP Input to executing program - DAT Output from executing program - DAT gen Input: highest existing generation Output: highest existing generation plus 1 When compiling a PASCAL program, you need specify only the if the file is: • Stored on the default device • Catalogued under the default directory name • A file type of PAS file name If more than one file meets these conditions, the compiler chooses the one with the highest generation number. For example, assume that your default device is PS:; your default directory is (CHEN>; and you supply the following file specification to the compiler: @F'ASCAL F'ASCAL>CIRCl.E The compiler searches device PS: in directory (CHEN>, seeking the highest generation of CIRCLE.PAS. The compiler then generates the file CIRCLE.REL, stores it on device PS: in directory (CHEN>, and assigns it a generation number that is one higher than any other generation of CIRCLE.REL currently in PS:(CHEN>. 8.3 CREATING A F'ROGRAM The first step in creating a program is to design and plan it. The TOPS-20 PASCAL Primer describes the use of PASCAL for the novice PASCAL programmer who is already familiar with higher-level programming language concepts. Many books exist that describe programming techniques, methods, and algorithms. 8-3 USING PASCAL ON TOPS-20 After planning the progr~m, you use an editor to create a file that contains the source statements. You use a text editor to create a source file. You can use EDIT, TV, or any other text editor to create the source file. For example, to create a PASCAL program that has the file name EXAMPL and a file type of PAS, you can issue the EDIT command as follows: (~EDIT EXAMF'L... PAS ~~ Input: EXAMPL.PAS O():lOO If this is a new file, an additional message is displayed indicating that a new file is being created. Because the EDIT command does not assume a file type, you must include the file type as part of the file name. The EDIT command runs the TOPS-20 default editor EDIT. The line number (00100) prompt indicates that EDIT is ready to accept input. For information on how to use EDIT, see the TOPS-20 EDIT User's Guide. You can also use any other editor to which you have access, for exampJe, the TV editor. To use TV, you can either type TV to TOPS-20, or you can define the logical name EDITOR: to be SYS:TV.EXE. For more information about the use of TV, refer to the TOP§-20 TV Edit.or Manual. After the program is created and edited, 8.4 it is ready to be compiled. COMPILING A PROGRAM After creating a PASCAL source program, you compile it. At compile time, you specify the source filers) and indicate any qualifiers you wish to use. Optionally, the compiler produces one or more object files, which are input to LINK, and one or more listing files. The listing files contain source-code listings, information about compilation errors, and optional items such as cross-reference listings. 8.4.1 The PASCAL Command To compile a source program, specify the PASCAL command and press the RETURN key. TOPS-20 then returns the PASCAL prompt, at which point you specify the file name and any switches. @PASCALG0 PASCAL)source-filename U/switch(es)TI 8-4 ~) USING PASCAL ON TOPS-20 where: source-filename specifies the source file(s) containing the program or module to be compiled. If you have one program split into several source files, you can specify these source files at the same time by separating the file names with a plus sign (+). If you specify more than one source file, the files nre concatenated and compiled as one program. /swi tch (es) indicates special processing to be by the compiler. performed In many cases, the simpJest form of the PASCAL command is sufficient for compilation. For other situations, however, PASCAL provides compiler commands and switches to specify special processing. PASCAL compiler commands give special instructions to the compiler. PASCAL compiler switches modify the compilation of the program. Section 8.4.2 describes the PASCAL compiler commands, 8.4.3 and 8.4.4 describe the PASCAL compiler switches. 8.4.2 and Sections PASCAL Compiler Commands Table 8-2 lists the commands to the compiler. Table 8-2: PASCAL Compiler Commands --------------------Command Purpose ------------------------------/EXIT Exits from the PASCAL compiler /HELP Displays a help messnge /RUN: Begins execution of the specified program /TAKE: Takes commands from the specified command file -------------------------------/EXIT The /EXIT command exits you from the compiler that were opened by the compiler. and closes all files /HELP The /HELP command displays a help message. /RUN:filespec The /RUN: command exits you from the compiler and begins execution of the specified program. Using the /RUN: command is the same as specifying the /EXIT command to the compiler and then using the operating system command RUN to execute the specified program. USING P~SCAL ON TOPS-20 /TAKE The /TAKE command takes commands from the specified command file. /TAKE command recognizes the default file type CMD. The Example 1 (~PAf:)CAL.. PASCAL)/TAKE: PLAN P{~SCAL) Assume that the command file PLAN.CMD contains the following: PLAN. PAS IN()FI...AG-··NON··-~JTANDAr~[I IL I ~JT I NG ~ The /TAKE: command causes the contents of PLAN.CMD to be executed. In this example, the source fiJe PLAN.PAS is compiled; display of warning messages for nonstandard features is suppressed; and a listing file is generated. Make sure the command file ends with a carriage-return/line-feed. After execution of the command file, you can give another command to the compiler. Example 2 PASCAL)SORTER.PAS PASCAL)/RUN: LINK * The compiler compiles the source file SORTER. PAS, and the /RUN: command is then used to run the LINK program. The /RUN: command exits you from the compiler and causes the LINK program to begin executing. The asterisk (*) is the prompt displayed by LINK. Example 3 @PASCAL PASCAL:>AVER.F'AS F'ASCAL:>/EX I T @ The EXIT command exits you from the compiler and puts you command level. 8.4.3 at TOPS-20 PASCAL Compiler Switches Table 8-3 lists the switches you can use with the PASCAL compiler. You can specify the switches following the file name or in source code comments. This section describes the effect of each switch on a PASCAL program. 8-6 USING PASCAL ON TOPS-20 Table 8-3: PASCAL Compiler Switches -----------------_._--------------------_. - Switch Purpose In Source Default /ABORT Causes the compiler to exist at the end of a compilation that contains errors No Off /BINARyr[:filespecll Produces a file. binary object No On /CHECK Generates code to for various conditions check error Yes On /CREF or /CROSS-REFERENCE Produces a cross-reference listing of identifiers Yes Off /DEBUG Produces information in the object file to be used wi th PASDD'r No Off /ERROR-LIMIT:n Stops compilation after the specified number of errors No 30 /FLAG-NON-STANDARD Issues warning messages for nonstandard features Yes On /LISTING[[:filespecl] Produces a source listing during compilation Yes Off /MACHINE-CODE Lists generated assembly language in source listing Yes Off /NATIONAL braces off Turns comment characters as Yes Off /WARNINGS Prints diagnostics warning-level errors fo rYes On ------------------------------------------------------/ABORT The /ABORT switch causes the compiler to exit at the end of a compilation that contains errors. This is useful when used with the /TAKE: command. The default is /NOABORT. /BINARY [:filespecD The /BINARY switch can be used when you want to specify the object file. The /BINARY switch has the form: /BINARY [:filespecD 8-7 the name of USING PASCAL ON TOPS-20 If you omit the file specification, the object file defaults to the name of the last source file, the default directory, and a file type of REL. You cannot specify this switch in the source code. You can disable this switch to suppress object code, for example, when you want to test only the source program for compilation errors. The default is /BINARY. /CHECK The /CHECK switch directs the compiler to generate co~e to perform run-time checks. This code checks for ilJegal assignments to sets and subranges, out-of-range array indices and case labels, and references to NIL pointers. The system issues an error message and terminates execution if any of these conditions occur. When this switch is disabled, the compiler does not generate code run-time checks. The default is /CHECK. for /CROSS-REFERENCE or /CREF The /CROSS-REFERENCE switch produces a cross-reference listing of all identifiers. The compiler generates separate cross-references for each procedure and function. To get complete cross-reference listings for a program, the switch must be in effect for all modules of the program. This switch is ignored if no listing file is being generated. The default is /NOCROSS-REFERENCE. You can specify this switch in the source code. Note, however, that the cross-reference listing for a portion of a procedure or function may be incomplete. /DEBUG The /DEBUG switch specifies that the compiler is information that can be used with run-time debugging. to generate The default is /NODEBUG. /ERROR-LIMIT:n The /ERROR-LIMIT switch terminates compilation after the specified number of errors, excluding warning-level errors, have been detected. The default limit is 30 errors. If this switch is disabled, compilation continues through the entire unit. You cannot specify this switch in the source code. The default is /ERROR-LIMIT:30. Note that, after finding 20 errors (including warning messages) on any one source line, the compiler generates error 255, Too Many Errors On This Source Line. Compilation of the line continues, but no further error messages are printed for that line. /FLAG-NON-STANDARD print The /FLAG-NON-STANDARD switch tells the compiler to program uses warning-level messages at each place where the nonstandard PASCAL features. 8-8 USING PASCAL ON TOPS-20 Nonstandard PASCAL features are the extensions to the proposed ISO standard for the PASCAL language that are incorporated in PASCAL-20. Nonstandard features include VALUE declarations and the exponentiation operator. Appendix D lists all the extensions. By default, /FLAG-NON-STANDARD is enabled. /LISTING The /LISTING switch produces a source listing file. It has the form: /LISTING [:fiJespecE You can include a file specification for the listing file. The default file specification designates the name of the first source file, your default directory, and a file type of LST. The compiler does not produce a Jisting file in interactive mode unless you specify the /LISTING switch. In batch mode, the compiler produces a listing file by default. In either case, the listing file is not automatically printed. /MACHINE-CODE The /MACHINE-CODE switch places in the listing file of the object code generated by the compiler. The compiler ignores enabled. this switch if the /LISTING a representation switch is not The default is /NOMACHINE-CODE. /NATIONAL The /NATIONAL switch causes the braces to have no speciaJ meaning. Therefore, if you specify the /NATIONAL switch, you cannot use braces as comment characters. Instead, you must use (* *). The default is /NONATIONAL. jWARNINGS The /WARNINGS switch directs the compiler to messages in response to warning-level errors. generate diagnostic By default, /WARNINGS is enabled. A warning diagnostic message indicates that the compiler has detected acceptable but unorthodox syntax, or has performed some corrective action. In either case, unexpected results may occur. To suppress warning diagnostic messages, disable this switch. Note that messages generated when the /STANDARD switch is enabled appear even if /WARNINGS is disabled. 8.4.4 Specifying Switches in the Source Code You can use switches in the source code to enable and disable special processing during compilation. When specified in the source code, switches have the form: (*$switch + ,switch + , ••• ;comment *) 8-9 USING PASCAL ON TOPS-20 The first character after the comment del imiter must be a doll~r sign (S); the dollar sign cannot be preceded by a space. Table 8-4 lists the switches you can specify in your source program. Note that you can optionally use a I-character abbreviation for each switch. The abbreviation is simply the first character of the switch name, except for CROSS-REFERENCE, which has X for an abbreviation. Table 8-4: Source Switches Abbreviation Full Command-Line Switch C CHECK CHECK L LTST LIST M MACHINE-CODE MACHINE-CODE N NATIONAL NATIONAL S STANDARD FLAG-NaN-STANDARD W WARNINGS WARNINGS X CROSS-REFERENCE CREF To enable a switch, specify a plus sign (+) after its name or abbreviation. To disable a switch, specify a minus sign (-) after its name or abbreviation. You can specify any number of switches. You can also include a text comment after the switches, separated from the list of switches by a semicolon. When specified in the source code, the LIST switch cannot contain a file specification. The listing file has the default specification described above. For example, to generate check code for only one procedure in a program, enable the CHECK switch before the procedure declaration, and disable it at the end of the procedure, as follows: <*$Ct ; enable CHECK for TEST1 PROCEDURE TEST1; onl~ *) END <*$C-;disable CHECK *) Command line switches override source-code switches. If, for example, the source code specifies NOWARNINGS, but you type /WARN on the command line, warning messages will be generated. NOTE When specifying the NATIONAL switch in the source code, always use the parentheses/asterisks combination (* *) and not braces { }. 8-10 USING PASCAL ON TOPS-20 8.4.5 Specifying Output Files The PASCAL compiler can produce object files and listing files, as well as compile the source code. You can control the production of these files with the addition of various file names and switches on the PASCAL command line. PASCAL produces an object file automatically, taking the name from the source file and assigning it the file type REL. To change the name of the object file, specify the /BINARY switch with a file name. To produce a listing file, you must specify the /LISTING switch on the PASCAL command line. You have the option of giving a file name with the /LISTING switch or taking the default, which is the name of the source file and the file type LST. Note, however, if you run PASCAL from a batch control file, you automatically receive a listing file. In this case, to suppress the creation of a listing file, specify the /NOLISTING switch in the batch control file. During the early stages of program development, it is often useful to suppress the production of object files until your source program compiles without error. To suppress the production of an object file, specify the /NOBINARY switch along with the source file. You can specify more than one source file at a time, to be concatenated and compiled. When specifying multiple source files, separate each one with a plus sign (+). Although you may specify more than one source file, you still receive one object file to load for execution. By default, the object file produced from concatenated source files has the name of the last source file on the command line. All other file specification attributes (device, directory, and so forth) assume the default attributes. Example 1 @PASCAL PASCAL)XXX+YYY+ZZZ Source files XXX.PAS, YYY.PAS, and ZZZ.PAS are concatenated and compiled as one file, producing an object file named ZZZ.REL. In batch mode, this command also produces the listing file ZZZ.LST. Example 2 @PASCAL PASCAL><S.GRAVES)MNP/LISTING The source file MNP.PAS in directory <S.GRAVES> is compiled, producing an object file named MNP.REL and a listing file name~ MNP.LST. The compiler places the object and listing files in the default directory. 8.4.6 Compiler Listing Format When you request a listing file (by specifying the /LIST switch, PASCAL produces a compiler listing. This section explains the format of the compiler listing illustrated in Figure 8-1. 8-11 • ct AVERAGE SCORE SOURCE LISTING LINE NUMBERS ADDRESS PROC DATA INST NO 100 000041 % PAS456 0 ex> I ~ 17-Aug-1983 CBL20:<MASELLA)AVER.PAS 200 300 400 500 600 700 800 900 1000 1100 1200 1300 1400 1500 1600 1700 1800 1800 0 LEVEL PROC STMT 0 0 Nonstandard Pascal: n$n OR 2 000215 0 1 0 3 000215 0 1 4 000220 1 0 5 000221 0 0 6 0 0 0400000 7 400012 0 1 8 400033 0 1 9 400034 0 1 10 400052 0 1 11 400061 0 1 12 400061 0 2 13 400076 0 14 400101 0 15 400104 0 16 400105 0 17 400113 0 18 400142 0 19 400172 0 0 0 .~ o o 11:23:32 PASCAL-20 1(611) Page o (1 ) STATEMENT. PROGRAM Averaqe Score (INPUT,OUTPUT); CEr'456---. *** BEGIN To ta 1 : = 0; Count := 0; WRITF,LN ('F,nter your scores. When done, type CTRL/Z.'); WHILE NOT EOF no BEGIN READLN (SCORE); Total ;= Scarp + To tell ; Count := Count + 1; End; AverageScore ::. Tolal / Count; (*to produce real results"") WRITELN ('The average score is: " AverageScore:4:1); END. 1.0 07 H Z GJ 'tl >' Cf} (J >' l' o 'tl 1 • ') 1 sec 0 nd s ( 7 5 5 1 in e s pe r min ute) . 17-Aug-1983 CBL20:<MASELLA)AVER.PAS Cf) I 10 o CD 11:23:32 PASCAL-20 1(1111) (] ) INSTRUCTION ADDRESS OPCODE 00 a 00 16 0 00 17 0 00 16 0 00 05 0 00 17 0 00 17 0 00 17 0 00 00 0 00 05 0 00 000000 400012 000000* 400013 000002' 400014 000000 0400015 000041' 400016 000005 400017 000000* 400020 777777 400021 000017 400022 000041' 400023 JFCL JSP G) MOVEM SETZ MOVEI PUSH PUSHJ ADJSP MOVE MOVEI 255 265 202 (t400 201 261 260 105 200 201 Jl t-3 Active options at end of compilation: NODEBUG,STANDARD,LIST,CHECK,WARNINGS,CROSS REFERENCF"G) MACHINE_CODE, OBJECT, ERROR_LP'lIT 30 LINE C Z 1 Nonstandard feature Last error (warning) on 1 ine AVERAGE SCORF. GENERATED CODE o C) o t'V Compilation time: 1 ===) CD in identifier in AVERAGE SCOREG) VAR Score, Total, \.ount : INTEGER; AverageScore : REAL; OPERAND{S) 00 PASLD% ACH,OO AC17,02 C)AC16 , ACOS,000041 AC]7,05 AC17,OO INP%IN AC17,777777 ACOO,l? AC05,000041 AVERAGE SCORE CROSS REFERENCE 17-Aug-1983 CBL20:<MASELLA)AVER.PAS 4 AVERAGESCORE AVERAGE SCORE COUNT INPUT • OUTPUT SCORE TOTAL 11:23:32 PASCAL-20 1(~11) Page 2 (1) 16 17 8 14 12 7 13 1 :3 3 13 14 Hi 13 16 GLOBALLY DEFINED IDENTIFIERS~e AVERAGE SCORE GENERATED CODE 17-Aug-1983 ] 1:23:32 PASCAL-20 CBL20:<~ASELLA)AVER.PAS 1(~11) (1) c::: U1 LINE (X) I I-' w INSTRUCTION ADDRESS OPCODE 523214520302 7331362607 Hi 625016361736 713124064746 351000000000 .427356462744 203635772744 203474367744 627465620256 643135620310 677354526100 723636062500 416512241)136 551340000000 000000000000 400153 400154 400155 400151) 400157. 40011)0 400161 400162 40011'13 400164 400165 40016') 400167 400170 400171 CONS'T'ANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT CONSTANT Figure 8-1: Compiler Listing Format H OPERAND(S) Z C) "0 ;t>o U1 n >' l' o Z t-3 o '"'0 U1 I N MR-S-3122-83 o USING PASCAL ON TOPS-20 The compiler listing sections: • in Figure 8-1 cont~jns Source-code listing - When you request a source code is listed by default. the following listing three file, the 1 isting, Machine-code listing - To generate the machine-code or the you must specify the /MACHINE-CODE switch, MACHINE-CODE + source switch. • Cross-reference listing - To gener~te cross-references for all identifiers used in the program, you must specify the /CREF switch. The numbers throughout this section are keyed to the numbers in Figure 8 -1. TITLE LINE - Each page of the listing cont~ins a title line. The title line lists the module n~me the nate and time of the compilation the PASCAL compiler name ~nd version number the listing page number and the file specification of the source f il e 0, o· 0, 0, 0, 8.4.6.1 Source-Code Listing - The lines of the source code are printed in the source-code listing. In addition, the listing contains the following information pertaining to the source code: 0 - • Editor line numbers If you created or edited the source file with an editor that automatically inserts line numbers, these line numbers appear in the leftmost column of the source-code listing. Editor line numbers are irrelevant to the PASCAL compiler. Note these are not the line numbers you specify to PASDDT for debugging purposes. • Line numbers The compiler assigns unique 1 ine numbers to the source lines in a PASCAL module. The symbolic traceback that is printed if your program encounters an exception at run time refers to these line numbers. Note these are the line numbers you use when working with PASDDT. Refer to Chapter 9 for information concerning the debugger. • Address The listing includes the octal address instruction on that line of source code. • Procedure number C) - PASCAL numbers each procedure in the listing file as it progresses down the source code, starting with 0 for the main program. • Procedure level Each line that contains a declaration lists th~ procedure level of that declaration. Procedure level 1 indicates declarations in the outermost block. The procedure-level number increases by one for each nesting level of functions or procedures. 0 - 0 - 0 - 8-14 of the USING PASCAL ON TOPS-20 • CD Statement level The] isting specifies a statement level for each line of source code after the first BEGIN delimiter. The statement level starts at a and increases by 1 for each nesting level of PASCAL structured statements. Specifically, the CASE statement, the REPEAT statement, Rnd the BEGIN/END block increase the statement level. The statement level of a comment is the same as that of the statement that follows it. ERRORS and WARNINGS -- The source-code listing includes information on any errors or warnings detected by the compiler. The actual message is printed beneath the error in the source code. In addition, the following items appear in the listing: • A circumflex (A) that points to the character position in the line where the error was detected t) • A numeric code, following the circumflex, that specifies the particular error On the following lines of the source listing, the compiler prints the text that corresponds to each numeric code • the The line number 'where the error was detected and line number of the previous line containing an error You can use these error line numbers to trace the error diagnostics back through the source listing. G). G) CD G SUMMARY -- At the end of the source listing, the compiler tells you how many errors or warnings were generated (if any), with the source line number where the last one occurred The compiler prints the status of all the compilation optjons and how much time was required for the compilation G) CD. CD 8.4.6.2 Machine-Code Listing - The machine-code listing (if requested with the /MACHINE-CODE switch) follows the source-code listing. The machine-code listing contains: CD - • Source line number A source line number marks the first object instruction that the compiler generated for the first PASCAL statement on that source line. • Octal representation of instruction _ representation of the object instruction. • Address instruction. • Opcode instruction. • Operand This contains the mnemonic and address field for the operation. fa fa This is the relocatable This is the mnemonic G - This is the operation address of the code for the accumulator For more information on machine-code instructions, DECsystem-lO /DECS,xSTEM-20. Processor Reference Manua 1. 8-15 octal refer field to the USING PASCAL ON TOPS-20 8.4.6.3 Cross-Reference Listing - The cross-reference listing (if requested with the /CREF switch) appears after the machine-code listing. It contains two s~ctions: fa - This section lists all • User-specified identifiers identifiers you declared. • Globally-defined identifiers This section lists PASCAL predefined identifiers that the program uses. CD - the the Each line of the cross-reference listing contains an identifier and a list of the source lines where the identifier is used The first line number indicates where the identifier is declared. Predefined identifiers are listed as if they were declared on ] in(~ 0 The cross-reference listing does not specify pointer type identifiers that are used before they are declared. G. fa. 8.5 LOADING A PROGRAM After compiling your PASCAL program, you load the object module(s) with the LINK program to produce an executable image file. Loading resolves all references in the object code and establishes absolute addresses for symbolic locations. This section describes the use of the LOAD command. 8.5.1 The LOAD Command To load an object module, specify the LOAD command general form: LOAD filename in the following [/switch(es) .•• ] where: filename specifies the input object file to be loaded. The file must be a REL file, created with the PASCAL compiler (or some other translator). /swi tch (es) specify input file options. The file specification must be typed on the same line as the LOAD command. If the file specification does not fit on one line, you can continue typing without pressing the RETURN key. The LOAD command runs the LINK program, which reads the REL file specified on the command line and loads it into memory. When LINK exits, it leaves your program in memory, ready to be SAVEd as an EXE file or to be STARTed. Th~ LOAD command can do a COMPILE command before running LINK. If you specify a file name to the LOAD command for which there is a source file but no REL file, the LOAD command automatically performs a COMPILE command first. See the TOPS-20 -------Commands Reference Manual -------LOAD command. 8-16 for more information on the USING PASCAL ON TOPS-20 8.6 EXECUTING A PROGRAM After you have compiled and linked your program, you can execute the object file with the START command; or you can save the file with the SAVE command, and then execute it with the RUN command. You ~an save time by using the EXECUTE command. The EXECUTE command acts by performing a LOAD command (which may start with a COMPILE command) followed immediately by a START command. So, instead of performing severa] separate steps of running the compiler, compiling your program, loading your program, and starting your program, you can compile, load, and start your program with a singJe command: (~EXECUTE f i 1 ename ~) Using the EXECUTE command does not save the executable image of the object file. The SAVE command stores a copy of the executabJe image in an executable file. The default file type that is created is EXE. After an executable image is saved, you can execute it with the RUN command. The SAVE and RUN commands have the form: (~~~AVE @f~UN f i 1 ename ~ f i 1 ename ~ You must specify the file name; default values are omit optional elements of the file specification. type is EXE. 8.7 appl ied if you Th e d e fa u] t f i 1 e EXAMPLES Example 1 (~F'ASCAL.. PASCAL> ~:;()HTEf~ /NOFLAG/L.. I ST I NG PASCAI...:>/EXIT @EXE SnRTEf~ f i] e This example uses the PASCAL command to compile the source SORTER. The /NOFLAG switch prevents display of messages about switch nonstandard PASCAL statements in the program; the /LISTING generates a .LST file of the compilation in your disk area. Example 2 @.PASCAL. PASCAL:>MERGER/DEBUG F'ASCAI, . >/EX I T @.LOAD MERGER/DEBUG @DEBUG MERGER The PASCAL command is used to compile the program with the debugger, PASDDT. The DEBUG command is used to load the compiled program and the PASCAL debugger automatically. The DEBUG command executes the program with PASDDT. 8-17 USTNG PASCAL ON TOPS-20 Example 3 frl LOAD PLAN ICOMF'I LE / Cf~LF @PFUNT PLAN. L.S"J (~ !:)TAJ:~T The LOAD command first compiles the program because of the /COMPILE The switch, then, if compilation js successful, loads the program. c ross- refe renee /CREF switch generates a listing file with information. The PRINT command prints the listing. The program is then executed with the START command. 8-18 CHAPTER 9 PASDDT: THE PASCAL-20 DEBUGGER The PASCAL-20 debugger, P~SDDT, provides the means to monitor and modify the execution of a PASCAL program. PASDDT provides symbolic debugging capabilities that allow you to read and modify the values associated with variables by referring to the PASCAL identifiers within your program. 9.1 RUNNING PASDDT To use the debugger, you must program. First, compile the switch in the command string: compile and load PASDDT with the source program and include the /DEBUG @PASCAL PASCAL>filename/DEBUG PASCAL>/EXIT @ Then, load the program along command: with PASDDT by specifying the The DEBUG command loads and starts the program with the debugger, PASDDT. currently in DEBUG @DEBUG filename memory, If you want more control over where the debugger is placed, or you have the need for more options, you can use the TOPS-20 LINK program directly. Refer to the LINK Reference Manual for TOPS-20 information. When running PASDDT, the source file with the extension PAS should be located in the same directory as the EXE version of the file. This should also be the directory to which you are connected when running PASDDT. If you have specified a file with the %INCLUDE directive, PASDDT looks for a file with the same name. 9.2 USING SYMBOLIC VALUES Symbolic values are the identifiers defined within the source program. PASDDT allows access to identifiers available only in the current scope, and performs recognition on these identifiers. You can specify a location in the source code by using the line number shown in the listing file created when the program is compiled. See Section 8.4.7. 9-1 PASDDT: THE PASCAL-20 DEBUGGER 9.3 SCOPE Scope is the range within the program in which a specific definition of an identifier exists. The scope corresponds to the part of the program in which the identifier can be used. Figure 9-1 shows the scope of three variables in program Modules. The scope of the identifier A (a global variable) is the entire program. The scope of variable B, declared in procedure Outer, is the entire procedure, including procedure Inner. The scope of variable C is limited to procedure Inner. SCOPE A PROGRAM Modu 1 (;~S (I NF'UT, OUTPUT); VAR A : INTEGER := 0; B F' t, 0 CE D LJ F~ E VAF~ B : (J 1..1 t f!' T' ; I NTEGEF~; C PROCEDUHE Inner, VAH C INTEGEf<; BEGIN (*beSin Inner*) END; (*end I nne T'* ) BEGIN (*besin Outf.·~r*) Figure 9-1: Scope PASDDT uses the concept of dynamic scnpe and their values. Dynamic scope is the of the program; the dynamic scope refers particular identifier is being used. procedure (a procedure that calls itself) same identifier. when accessing identifiers scope in relation to the use to the level at which a For example, a recursive has multiple scopes for the PASDDT represents the scope of an identifier with a positive integer. Global data has a scope of 1. Each nested level from that has a scope of one greater than that of the level from which it is called. The following example is a recursive function that calculates factorials. 9-2 PASDDT: THE PASCAL-~O DEBUGGER PF<OGI:<AM Ca 1 cu 1 ate (I NPUT, OUTPUT) , VAR Answer~ Num : INTEGER; FUNCTION Factorial (Number BEGIN WHILE Number > 0 DO F i3 C tor i a 1. : ::" N1,,1 IT! b E\ T' BEGIN Answer INTEGER) INTEGEF< , * F act 0 r :i. a 1 ( NU IT! tl f.~ Y' .... 1), := Factorial(Num); ENDt When Factorial is called from the main program, the value of Num is passed to Number. Until Number is equal to 0, the function Factorial continues to call itself; the value of Number is decremented by 1 each time the function calJs itself. Assume that the value 3 is passed to Number. Number then has the value of 3, then of 2, then of 1, then of O. Each call to itself represents another level of dynamic scope. Number has a scope of 1 the first time it is called; a scope of 2 the second time it is called, and so on. 9.4 PASDDT COMMANDS The following sections describe each of the default radix for all purposes is decimal. PASDDT commands. The PASDDT uses the facility of recognition and guidewords. Recognition permits you to type enough of the word or identifier to be unique. For example, you can type CL to specify the CLEAR command. You can also use recognition with identifiers you have used in the program. For example, if you have defined the identifiers NewList and NewTABLE, you could use NewL and NewT, respectively, to specify these identifiers. PASDDT also provides guidewords when you press the ESC key. The guide words indicate what you should enter next. In the following sections, guidewords are displayed in parentheses. You do not need to type the guidewords or the surrounding parentheses in the syntax. In addition, PASDDT displays the options that you can enter when you type a question mark (:'). For more information about recognition and guidewords, refer to the TOPS-20 User's Guide. 9.4.1 ASSIGN ASSIGN assigns a value or virtual address to the specified identifier. The format is: ASSIGN (VARIABLE or ADDRESS) {user identifier} octal address (:=) {constant } octal value where: user identifier is a variable name in the active scope. octal address is a virtual address in the user program. 9-3 PASDDT: THE PASCAL-?O DEBUGGER constant is a value with a simple data type INTEGER, REAL, CHAR, BOOLEAN, DOUBLE, user-defined enumerated type. octal value is the value address. to be placed in the of or octal Example PASDDT)ASSIGN New_Int (:=) 20 This example assigns the value of 20 to user identifier New Int. 9.4.2 BREAK BREAK sets a new breakpoint at a specified location or resets an existing breakpoint. During a debugging session, when the program reaches the location specified, it stops execution, thus allowing you to perform debugging operations. You can set a maximum of 20 breakpoints. To set a new command: BREAK breakpoint, (AT) use line number the [(NAME) following format of the BREAK break identifierD where: line number is a line number corresponding to a line in the source code. These line numbers are found in the listing file generated when you compile the program. break identifier is the name you associate with the breakpoint. Each breakpoint identifier can contain any number of characters, but the first nine characters must be unique. The break identifier can contain all characters except an underscore ( ) or dollar sign ($). Note that you cannot set a breakpoint in the declaration section of a program. If you do, PASDDT sends you an error message and does not set the breakpoint. To change the status of a breakpoint from CLEAR (Section the following format of the BREAK command: BREAK 9.4.3), use (AT) {line number } break identifier where: line number is the line number of the breakpoint that you want to reactivate. break identifier is the name of the reactivate. breakpoint you want to Note that you can find out the status of breakpoints by displaying them with the DISPLAY command. See Section 9.4.4 for information on the DISPLAY command. 9-4 - - - - ---------------- PASDDT: THE PASCAL-20 DEBUGGER The following rules apply to the use of BREAK: If you specify a following happens: • break identifier, but not a line If there is already a breakpoint with this is used. number, the identifier, this breakpoin~ • If there is no breakpoint occurs. If you specify a following happens: line number, with but not assigned this identifier, an error a break identifier, the for this location, that • If a breakpoint is breakpoint is used. • If a breakpoint has not been assigned, a established with the identifier NO NAME. If the command specifies both a line number and the following happens: new a breakpoint break is identifier, • If a breakpoint has already been assigned for this location with this identifier, the previously defined breakpoint is used. • If a breakpoint has already been assigned for with a different identifier, an error occurs. • If a breakpoint has already been assigned at another location with this identifier, and no breakpoint has been set at this location, PASDDT prints a warning message. PASDDT then asks if you want to override the address associated with that breakpoint. If so, the previous breakpoint is discarded, and a new breakpoint is declared with the given identifier and location. this Note that you must use the PROCEED command after each break program to continue. PROCEED is described in Section 9.4.7. location for Note the following example: PASDDT)break 10 first PASDDT)displa~ break BREAK POINT(S): Name = FIRST Break Address 000000400044 Line Number 10 Status BREAK PASDDT)proceed »BREAK:FIRST PC AT VIRTUAL ADDRESS 00000040044 PASCAL LINE NUMBER 10 LINE 9: Count:= O~ LINE 10: WRITELN ('Enter ~our scores. When done, LINE 11: WHILE NOT EOF DO PASDDT) 9-5 t~pe CTRL/Z.'); the PASDDT: THE PASCAL-20 DEBUGGER As shown in the previous example, PASDDT automatic~lly displays three lines of source code at a breakpoint. See the SET command, Section 9.4.9, for details of controlling the display of source code when a breakpoint is reached. 9.4.3 CLEAR CLEAR turns off breakpoints and tracepoints set TRACE commands. The format is: CLEAR (AT) jline number } \break identifier with the BREAK and [(NAME) bre~k identifier] whe re:: line number is the line number in the source code the breakpoint or tracepoint is set. break identifier is the name of the breakpoint or associated with the line number. where tracepoint You can specify either both the line number and associated identifier, just the line number, or just the bre~k identifier. break The CLEAR command does not delete the breakpoint or tracepoint; the CLEAR command merely turns it off. Also, although you have cleared a breakpoint or tracepoint, it is still counted in the total 20 allowed. To delete a breakpoint or tracepoint, use the REMOVE command, Section 9.4.8. If you want to check the status of breakpoints and tracepoints, use the DISPLAY command, Section 9.4.4. Note the following example: PASDDT:::bT'€:.'ak 11 onp PASDDT)break 12 two F' A S [t D T :::.0.1 :i. S p 1. a'.:l b rea k BREAK POINT (~:» : Nam'f.? := ONE Break Add T'(-::'ss Lin,:? Numb<::.' Y' Status Nc31T'E' 000000400062 :l1 I-:lF<LAt( ::.:: TWO Break Acid T'€~SS Line NlJlTlbe r Statu~:; 000000400071 :t2 BRE(.lt( PASDDT:::clear 11 PASDDT:::di SF' la~:I break BREAI\ PO! NT ( S) : :::: ONE Name B real>:. Add T'€:'S~:; Line Number Status 000000400062 11 Name :::: TWO Break Addrpss Line Number Status 000000400071 12 OFF BRE/~K 9-tS PASDDT: THE PASCAL-20 DEBUGGER PASDDT)clear two PASDDT)displaY break PO I NT ( [» ! m~EttK NalYt(·:·~ :::: ONE B r f? a k A (! d T' f:~ ~; !:; Line Nl..IlTtb€·~ l' OO()()0040()062 1:1. OFr Status ~:: TWO NalTtf.~ B T'E~ak Add rE.'S!:; L.. i ne NUlYlt:.\f.-~ T' 000000400()71 1 ':) OrF L,t.atu5 PASDDT> t,l T'f·~ak 12 PASDDT>disp}ay break BREAK F'DINT(S): Na"ff.·~ :::: ONE Break Add T'E.'!;;!:; Line NUITtbe T' 000000400062 11 OFF Status Name :::: TWO BT'eak Addre!:;s I... i ne Numbe T' 000000400071 12 Status PASDDT) e;.~ 9.4.4 BREAK DISPLAY The DISPLAY command has three functions: 1. To show the status of breakpoints and tracepoints 2. To show the calling sequence of procedures and functions 3. To show a line (or range of lines) To DISPLAY information about following format: breakpoints DISPLAY B [REAK-IDENTIFIERD of the source code and tracepoints, use the [break identifierD where: B [REAK-IDENTIFIERD indicates that you want breakpoints and tracepoints. break identifier is the name of a particular breakpoint or tracepoint. If you do not specify a break identifier, PASDDT displays information about all of them. to display The information you receive includes the name of the breakpoint, the line number of the breakpoint, and the status of the breakpoint (ON or OFF) • 9-7 PASDDT: THE PASCAL-20 DEBUGGER Note the following example: F't-lf; VI:! T>f."j:i ~:;F' 1. d ':1 r: F~ E f~ 1< POI NT ( ~:;) : Name LI r E' aV FIRS1' ~ I: Y' f~ d k Ad (I l' f~ ~:; ':; I... :i, f"tf~ Nl..llTil.'.l(':'~ Y' ~:; t, d t I..J ~:; Name o() 0 () 0 0 0 () () :5 ') ::,:j .1.9 Bf~EAK SECOND :0 r E' a k f1 cli.".i Y' f~ ''', ':; I... i. n e N UITI t . . C~ r O()()O O()OOO 4 ~:i 2 23 ~:;t,atl,I<:; THAC[ = THIRD N~m0 n r'eak L i f"t(,~, Ad(1 T'f?~:;S O()()O()()0006:1.? 37 NUITI~:.le T' PASDDT>displa~ break second POINT (~;) : BF,EAK Name = SECOND Break Address 000000000452 I... i n f:~ N u mb c,~ T' 23 Status TRACE To DISPLAY the calling sequence of procedures and functions, following format: DISPLAY (OPTION) 1 [NVOCA1'ION-STACK] use {integer} [{/STATIC * /DYNAMIC the }n where: I [NVOCATION-STACK] indicates that you want to display calling sequence of your routines. the integer is a decimal number representing many routine calls to display. how * routine indicates that you want all to the main calls displayed back program. /STATIC causes the static level of the routines to be displayed as they were defined in the user program. /DYNAMIC causes every invocation of a routine be displayed. This is the default. to The information you receive includes the calling sequence, the static level of the procedure or function, and the address at the time of the display. 9-8 PASDDT: THE PASCAL-20 DEBUGGER Note the following eXAmple: PASDDT)dispIBY invocation-stack */static ~:; PI?OCEDUI:<E NAME Gf< 0 CE f< Y .... D 11... 1... PAf:;DDT>d i !:;F']. a\~ i nvoc TAT J C I... E V[ I... ADDr<Ff:;~:; OOO:L40 :I. *1 (l':~nalTl i c ~:;TATIC r-f<OCE DUf<[ NAt'1E C; F< [) C [ F< Y.... n J 1...1... I... EVEL.. ADDf~'ES~:; O()O:l.40 l PA~:;DDT) To DISPLAY lines of following format: DISPLAY source code in (OPTTON) S [OURCE-LINEn the current line number scope, use the [/RANGE:integern where: S [OURCE-LINE n indicates that you want to display a ] ine the source code. line number is an integer representing a line in the source code. You will find these numbers in the listing file. /RANGE: is an optional value indicating that you want to display more than one line of source code. integer is a decimal number indicating how many lines of source code to display. DISPLAY prints the source code of the line number you specify and other lines included in the range. of any Note the following example: PrY:lDDT >d i Sp 1 a~:j ~)C)l.1 T'Cf? ~)I T'an9f?: 10 LINE ::.=;: YP~;;, ... ND :::: (YP~:; , No), LINE 6: LINE 7: I... INE B! (* Defines data type Yes_No with valups Yes and No *) VAR LINE 9: LINE :LO: LINE :L1: LINE :1.2: LINE 13: ItplTI ...YT'ic(", , Total, C () 1..1 F' [) n .. _A III C) U n t An!:> : Yes .... Nc); <*Declares three real variab:l.ps*) <* Declares a variable, An~; ¥ of t~IPP Yes .. _No ~:;ubt Dta:l. y *) CouF'ons: REAL.. : :=: O. (); LINE :J.4: PAf~DDT> 9.4.5 EXIT EXIT halts execution of the program. EXIT 9-9 The format is: PASDDT: THE PASCAL-20 DEBUGGER Note the following ex~mp]e: F' It.) S nn T:> F X I T C F:' U t :i. IYI C-' : U! () () • :I. <:.) J. d F' ~:; (.:.) (1 t i ITI P : [ () 3 • :3"7 This exits you from PASDDT an~ puts you at TOPS-20 command level. CPU time and elapsed time are ~lso displ~yed. 9.4.6 The HELP HELP displays a help message. HELP (with PASDDT) The format is: [command name] Note the following example: [HELP::! H [ I... F' [ C (] HlITI a n ,j n a ITI (.:.~ T h i. ~:; C () ITIIT! l ~~ F' f:~ / wit h • 0 T' T' P t u T' n :I and a:l. low ~:; t h f~ foIl D I-J [~d HE l.. F' / T \:~ P e i:l 1..1 ~:; e l' t n b ~~ the G I.J est ion IT! a T' k ~:1 f.~ t (/? /) h (~) 1. F' wit h C () !TIm a n (.1 t (] Sf:) e ~~ C) PAn 1:1 11 T • u wan t h f;;> 1. p t h (-? co !TIm and s that are available. PA~)DDT> P;': This displays help messages about all of the PASDDT commands. 9.4.7 PROCEED PROCEED initiates or continues execution of the program until a breakpoint is reached or the user program terminates. The format is: PROCEED (with USER Program) Example 1 i~ PASCAL. PASCAL>TEST.PAS/DEBUG FASCAL:>/EXIT TEST (~, DEBUG FAt;DDT> F'f<OCEED This example shows source program TEST.PAS being compiled, loaded, and started. PROCEED initiates the execution of the program. Example 2 (;1 PASCAL @PASCAl..>EXAMPL IDEBUG f'ASCAL> lEX I T @LOAD EXAMPL.REL,SYS:PASDDT.REL (;l SAVE EXAMPL (!) F<UN EXAMPL PASDDT>PROCEED 9-10 PASDDT: THE PASCAL-20 DEBUGGER This example compiles and loads the program EXAMPL. Loading PASDDT.REL with the program EXAMPL causes a copy of PASDDT to become a part of the executable file EXAMPL.EXE. PROCEED initiates the execution of the program. Example 3 p f:':j ~:; II II T >P H() C E E D This example causes the program to resume execution after stopping a breakpoint. 9.4.8 at REMOVE REMOVE deletes breakpoints and tracepoints completely. REMOVE (AT) {Jine number } break identifier [(NAME) The format is: break identifier] where: 1 ine number is the line number in the source code you set the breakpoint or tracepoint. where break identifier is the name of the breakpoint or tracepoint. You can specify either a line number followed by the break identifier associated with that line number, just the line number, or just the break identifier. Note the following example: PASDDT>b reak 10 PASDDT>displa'3 break rmFAK POINT (S) : Name : <NONAME> Break Address 000000400044 Line Number 10 Status BREAK PASDDT>remove 10 F'ASDDT>d i SF' 1 <3'3 b r'eak NO BREAKPOINTS SET F'ASDDT>E'~'~ 9.4.9 SET The SET command has four functions: a 1. Turning on automatic displaying of source breakpoint is executed. This is the default. 2. Telling PASDDT how many lines to display when a breakpoint is executed. The default is three. 9-11 code when PASDDT: THE PAS~AL-20 DEBUGGER ]. Telling PASDDT which separately compiled module to use in terms of setting breakpoints and gaining information about the user program. When PASDD~ starts up, the default is the main program. 4. Setting the level of jnformation displayed default is VERBOSE. To SET the automatic displaying of source code following format: on by PASDDT. The or off, the use SET (OPTION) {A [UTO-DISPLAY D l NO-A [UTO-DISPLAyD ( where: A.UTO-DISPLAY turns on the automatic displaying of source code at a breakpoint. This is the default. NO-AUTO-DISPLAY turns off the automatic displaying of code at a breakpoint. source When AUTO-DISPLAY is set, PASDDT displays the line of source code at the breakpoint. If your terminal is slow or you are using a dial-up line, you may want to turn off displaying the source code with NO-AUTO-DISPLAY. Note the following example: .10 set no-ooauto PASD[lT>bT'f.~ak PA~)DDT> PAf:;DDT> p T'oc(~ed »BF,EAK: PC AT VIRTUAL ADDRESS 000000000416 PASCAL LINE NUMBER 10 PASDDT>break 12 PASDDT>set auto PASDDT>PI'oC Enter YOUI' SCOI'es. When done, t~pe CTRL/Z. 23 »BREAK: PC AT VIRTUAL ADDRESS 000000000443 PASCAL LINE NUMBER = 12 LINE 11: WHILE NOT EOF DO LINE 12: BEGIN LINE 13: READLN (Score); To SET the number of lines to automatically display, use the following format of the SET command: SET (OPTION) W [INDOwD n where: lrlINDOW indicates that you want to set the number of lines of source code to display at a breakpoint. n is a decimal integer specifying how many lines of source code to display. The default is three. The window is centered around the line on which the breakpoint is set. 9-12 PASDDT: THE PASCAL-20 DEBUGGER Note the following ex~mple: PASDD1)set window 10 Pt,!:;ODT>p I'OC 4~:.:j »Bf<EAI< ~ PC AT VIRTUAl... ADDRESS 000000000443 I... J NF NUMBEI< I... INE "?! BEGIN I... 1 N[ n: Tot a :I. !:::: () y I... J N E (1': C 0 u n t. ~:::: () y 1..1F~ I TEL. N (I E n tt-:~ l' ~~ 0 U J' I...JNE :1.0: LINE :I. 1 WHII... E NOT FOF DO 12 P(.)!:;C(~L · LINE LINE 13: LINE · LINE :1.2: F~ [ A DI... N Count :1. !:.=.; : · Wh €.~ n don e, t ~:t F' peT RI... / 1 • I ) ; BEGIN :1.4 LINE 1 f.) ~:; C 0 J' e !,;. (!:) COl' e ) Y Total := Scorp + Total; := Count + 1; Endy To SET the name of the module where PASDDT can find information relevent for debugging purposes, use the following format of the SET command: SET (OPTION) M [ODULE] module name where: MODULE indicates that you want to specify of a separately compiled module. the name module name is the identifier after the word PROGRAM or MODULE in the source file. At start-up, the default is the main program. Note the following example: PASDDT>spt module ? MODULE NAME AVERAGE_SCORE PASDDT>set module average_score F'ASDDT> To SET the level of information displayed by PASDDT, use the following format of the SET command: SET (OPTION) V [ERBOSITY] (OF TYPEOUT) {V [ERBOSEll } BRIEF lJ where: VERBOSITY indicates that you want to change of information displayed. VERBOSE displays the most information. default. BRIEF dispJays ~ the This level is minimal amount of information. 9-13 the PASDDT: THE PASCAL-20 DEBUGGER Note the following example: PA~;DD T>~:;.,·:·.>t VP r;·:.lo';; I TY (OF TYPEOUT) b T' i. e'f PA~:;DnT::F' rucp ::.:it:·, :> >Br~FA~<: I... I NE NUMBEI:~ :1.2 BEGIN 8: Total:= 0; Co u n t ; ~o () y 9: :LO: ("II:~ I TEl... N (/ En t P l' ~:J (.") 1..1 r .; C () T' f' s. It! ("IH TLE NOT FOF no F'(~~:;C()/... LINE "7! LINE I... INE LINE LINE LINE :L?: I... INE 13: LINE 14: LINE Wh p n (Ion E', t ~:~ p (.:.) C T f< l.. / Z • ' ) , BEGIN f~ E A 1:1 L.. N :l~::j: Count (S COl"' e ) ; Total := Score t := Count t 1; Total; Enrj y LINE 1,'.): PAf;nItT>Sf::,t w:i nl.".luw ~.:J F'(':)~:;DDT)1-"' roc /U »BF~EAK : PAbCAL.. I... I NE NUMBER LINE :LO! LINE :1.1; 12 WRITELN ('Enter ~our scores. ~JH:r LE NOT [OF DO When done, t~pe CTf<L/Z.'); BEGIN LINE 12: LINE 13: F~E(.:IDLN LINE 14: (SCOT'f.~); Tutal := Score t Total; PASDDT>t');.: i t 9.4.10 SHOW The SHOW command prints the current format of the SHOW command is: value of an identifier. The SHOW (VARIABLE OR ADDRESS) {user identifier} octal 0r'ldress where: user identifier is the name of scope. octal address is A virtual address in the user program. (This is not the address shown in the listing a variable in the current f i 1 e.) Note that, when you set a breakpoint, PASDDT automatically displays three lines of source code, unless you specified SET NO-AUTO-DISPLAY. You can then see any identifiers that are declared for the current scope of the user program with the SHOW command. You can also type a question mark (?) to the SHOW command to see what identifiers are available. 9-14 PASDDT: THE PASCAL-?O DEBUGGER Note the following example: P (.~ ~:; 11 D T ::- /..1 r (7.' a k :I. () r'A~:;DDT:> F' rocc:'f.·~(i :> :> nF;: F (~,.( : PC AT VIRfUAL ADDRESS 000000400044 PASCAl... I... I NE NUMBE'~ 1 () LINE 9: Count:= ()~ LINE 10: WRITELN ('Enter ~our scores. When done, t~pe CTRL/Z.'); LINE 11: WHILE NOT EOF DO PASDDT:>show ? VIR1UAL ADDRESS o J' F' A~; CAL. VA f~ J f~ [: l.. Eon e 0 f the f 0 1. low i n ~~ : AVFF~(~GESCDf~E AVERAGE .... SCURE COUNT INPUT OUTPUT SCORE TOTAL F'f.1SDDT> (~,how seo T'C';'> () VALUE TYPE INTEGER ADDRESS 037060 PA~:;DDT> show count ljALUE o TYPE INTEGER OT?062 PASDDT>show input F :i. I (-? is OPEN fo l' T'E~ad i ng File is a TEXT file F :i. :I. p i ~:; TTY: File is the standard Fi If? name F'ASDDT> e;< TTY: 9.4.11 INPUT file TRACE TRACE sets a new tracepoint at a specified location or resets an existing tracepoint. When the program reaches the location specified, PASDDT prints a message indicating that a trace was placed on this line. Unlike the BREAK command, TRACE does not halt program execution or print source code. You can set a total of 20 tracepoints and breakpoints. Clearing them does not delete them from the count. To set a new command: tracepoint, TRACE (AT) use line number the [(NAME) following format of the TRACE trace identifierD where: line number is the line number associated with the line of source code that you want to trace. This line number can be found in the listing file. trace identifier is the name you want to associate with the tracepoint. Each identifier can contain any number of characters, but the first nIne characters must be unique. The identifier can contain all characters except underscore ( ) and doLlar sign ($). 9-lS P~SDDT: THE PASCAL-?O DEBUGGER To reset a tracepoint that you have turned off with CLEAR 9.4.3), use the following format of the TRACE command: TRACE (AT) J line number (Section } tbreak identifier where: line number is the line number of an existing that you want to reset. break identifier is the name of an existing you want to reset. The following tracepoint tracepoint that rules apply to the use of TRACE: If you specify a following happens: trace identifier, but not a • If there is already a tracepoint with this tracepoint is used. • If there is no tracepoint occurs. If you specify a following happens: line number, with but not number, the identifier, this identifier, an error a trace identifier, the for this location, that • If a tracepoint is tracepoint is used. • If a tracepoint has not been assigned, a new tracepoint is established with the identifier NO NAME. You can have more than one tracepoint with the name NO NAME. If you specify both following happens: a line assigned this line number and a trace identifier, the • If a tracepoint has already been assigned for this location with this identifier, the previously defined tracepoint is used. • If a tracepoint has already been assigned for with a different identifier, an error occurs. • If a tracepoint has already been assigned at another location with this identifier, and no tracepoint has been set at this location, PASDDT prints a warning message. PASDDT then asks if you want to override the address associated with the previous tracepoint. If so, the previous tracepoint is discarded, and a new tracepoint is declared with the given identifier and location. 9-10 this location PASDDT: THE PASCAL-20 DEBUGGER Note the following example: PASDDT>trace 10 F'r:":)f;DDT> p 1'ocf.~pd one »Tr~ACF: ONE PC AT VIRTUAL ADDRESS PASCAL LINE NUMBER Ent~:~ l' ~:IOU r ~:;co T'P~;;. 000000400044 :1.0 Whf.:'n (lOne, t\:lf"e CTF~I... /Z. 7:':; 44 Dr; '·'7Thf~ ave ra!.:.!p ~:;co r'(-;-:o :i~;: 69.3 9-17 APPENDIX A PASCAL MESSAGES ._------------Table A-I: Run-time Errors ? PRTOOI Value not within subrange of variable in assignment. ? PRTOO2 Case selector out of range. ? PRTOO3 Array index out of bounds. ? PRTOO4 Conformant array index out of bounds. ? PRTOO5 Size of conformant arrays incompatible. ? PRToor; NIL pointer value at runtime. ? PRTOO7 Attempt to divide by O. ? PRTOO8 Mod with 0 or negative value. ? PRTOO9 Set value out of range in assignment. ? PRTOIO Set element out of range in assignment. ? PHTOll Stack expansion faiJed - No for stack space. ? PRT012 Memory expansion failed - No more memory available. ? PRT013 DISPOSE called with NIL pointer. ? PRT014 Page creation failed, error code ? PRT015 Page destroy ? PRTOII1 Insufficient initial memory - ? PRT017 Fatal error PC number. ? PRT018 Fatal error - illegal memory reference user PC number. ? PRT019 Fatal error PC number. ? PRT020 Fatal error PC number. illegal memory write detected at user ? PRT021 Fatal error numbe r. non-existent page detected at user PC f~iled, ilJegal - more memory available = number. error code = number. cannot start program. instruction detected at detected user at illegal memory read detected at user A-I PASCAL MESSAGES Note that errors PRTOl7 through PRT021 are probably caused by improper use of an array or pointer variable. If you receive one of these errors, try compiling the program with the /CHECK switch. Table A-2: I/O Errors ? PIOOOI User buffer overflow. File in error: filespec ? PIOOO2 Line limit exceeded. File in error: filespec ? PIOOO3 File not open for reading. File in error: filespec ? PTOOO4 File not open for writing. File in error: filespec ? PIOOO5 Field width <= zero. File in error: filespec ? PIOOO'S String write error. File in error: filespec ? PIOOO7 Integer write error. File in error: filespec ? PIOOO8 Field width < zero. File in error: filespec ? PIOOO9 Attempt to read past EOF. File in error: filespec ? PIOOlO Integer read error. File in error: filespec ? PIOOlI String read error. File in error: ? PIOOl2 Illegal character in filespec ? PIOOI] Attempt to RESET(output). File in error: filespec ? PIOO14 Attempt to RESET(input). File in error: filespec ? PIOO15 ? PIOO U:; number in error: to reset/rewrite uninitialized file. File in error: filespec ~ttempt Error in filespec opening binary ? PIOOl8 Error in fiJespec writing to PIOO19 Error in filespec closing binary ? File Integer overflow. File in error: filespec PIOOl7 ? I/O. filespf~c file. object File in error: file. File in error: filc. File in error: ? PIOO20 Delete file error. File in error: filespec ? PIOO21 Include/Exclude file error. File in error: filespec ? PIOO22 Attempt to use FIND on text filespec ? PIOO21 Attempt to filespec ? PIOO24 Field width too error: filespec FIND file. File in error: a negative record. File in error: small A-2 for number output. File in PASCAL MESSAGES ---------------------------------------------_._--------Table A-2: I/O Errors (Cont.) -------------? PIOO25 Scalar out of range. File in error: filespec ? PIOO2f) Attempt to open/close INPUT filespec file. File in error: ? PIOO27 Attem~t file. File in error: to close OUTPUT ? PIOO2R Attempt to filespec write to READONLY file. File in error: ? PIOO29 Attempt to open already opened file. filespec File in error: ? PIOO30 At tern p t toR EWR I T E ( 0 u t put). F i 1 e in err 0 r: f i ] e s pe c ? PIOO31 At~::empt to REWRITE (input) • File in error: filespec ? PIOO32 Exponent too large. File in error: filespec ? PIOO33 Exponent too small. File in error: filespec ? PIOO34 Reset error filespec ? PIOO35 Scalar is all blanks. File in error: filespec ? PIOO3(j Attempt to read past enct of filespec File in error: ? PIOO37 Attempt to readln/writeln to a binary file. err-or: filespec File in ? PIOO40 PAGE called with fjle err-or: filE~spec File ? PIOO42 EOLN called when EOF true. ? PIOO43 Testing EOF filespec ? PIOO44 Too many open files. ? PIOO45 Attempt to filespec filespec File on not found. line. opened unopened File NOCARRIAGE. File in error: file. RESET new internal in error: File file. in filespec in e r ro r: File in error: Compile-Time Errors ? PASOOI Error in simple type The declaration for a base type of a set or the index type of array contains a syntax error. ? PASOO~ an Identifier expected The statement syntax requires an found. A-3 identifier, but none can be PASCAL MESSAGES ? PAS003 tlpROGRAM tI or tlMODULE tI expected The statement MODULE. ? PAS004 tI) tI syntax requires the reserved word PROGRAM or expected The statement syntax requires the right-parenthesis character. ? PAS005 11:11 expected The statement syntax requires a colon character. ? PASOOf) I I I eg a] symbol as a misspelled such as a The statement contains an illegal symbol, such reserved word or ilJegal character. ? PASOO7 Error in parameter list The parameter list contains a syntax error, comma, colon, or semicolon character. ? PASOO8 1I0F II missing expected 1'he statement syn ta x requires the reserved word OF •. ? PASClO9 II (II expected The statement syn tax requires the left-parenthesis character. ? PASOIO Error in type The statement syn tax requires a data type, but no type identifier is present. ? PASOll II r II expected The statement syntax requires the left square bracket character. ? PAS012 II 1 II expected The statement syn ta x requires the right square bracket character. ? PAS013 IIENDII expected The compiler cannot find the delimiter END, which marks of a compound statement, subprogram, or program. ? PAS014 the end "., " expected The statement syn tax requires the semicoJon character. ? PAS015 Integer expected 'rhe statement syn tax requires an integer. ? PAS016 11=11 expected The statement syntax requires the equal sign to separate a constant identifier from a constant value or to separate a type identifier from a type definition. A-4 PASCAL MESSAGES ? PASOl7 "BEGIN" expected The compiler cannot find the delimiter beginning of an executable section. ? PAS018 " BEGIN, marks the " expected The compiler cannot find the symbol, between the endpoints of a subrange. ? PAS019 which which is required Error in field list The field list in a record declaration contains a syn tax error. ? PAS020 " , " expected The statement syntax requires a comma. ? PAS021 Empty parameter (successive " , " ) not allowed The parameter list attempts to specify parameter, or contains an extra comma. ? PAS022 IJlegal a null or missing (nonprintable) ASCII character The program contains an illegal character that is not a printable ASCII character. ? PAS023 "," or ")" expected The statement syntax requires right-parenthesis character. ? PAS024 '" either a comma or a '" expected The statement syntax requires two quotation marks. ? PAS050 Error in constant A constant contains an illegal character or is improperly formed. ? PAS051 ":=" expected The statement syntax requires the assignment operator. ? PAS052 "THEN" expected The compiler cannot find the reserved word THEN to IF-THEN statement. complete the The compiler cannot find the reserved word UNTIL to complete REPEAT statement. the ? PAS053 ? PAS054 "UNTIL" expected "DO" expected The compiler cannot find the reserved word DO to complete the FOR statement or the WHILE statement. ? PAS055 "TO" or "DOWNTO" expected The compiler cannot find the FOR statement. rE~served A-5 word TO or DOWNTO in the PASCAL ? PAS05A MESS~GES Invalid expression The statement syntax requires an expression, but the first symbol the compiler finds is not Jegal in the expression. ? PAS059 Error in variable A reference to an array element or record field contains a syntax error. ? PAS060 "ARRAY" expected The compiler cannot find the reserved definition. ? PASO~l PASO~2 ARRAY in the type reserved word PROCEDURE or "PROCEDURE" or "FUNCTION" expected The statement syntax requires FUNCTION. ? word the Internal compiler error An internal error has been detected. ? PAS095 Functions "BIN", "OCT", or "HEX" not allowed in this context The context does not allow the functions BIN, OCT, or HEX. ? PAS096 File component may not exceed ~5515 words The file component is larger than 65535 words. ? PAS097 Error count exceeds error limit. Compilation aborted. The number of errors exceeded the limit you specified. ? PAS099 End of input encountered before end of program. aborted. ? PAS100 Array size too large A declared array is larger than 2,147,483,647 2,147,483,647 bits for a packed array. ? PAS101 bytes or Identifier declared twice An identifier is declared twice within a You can redeclare identifiers only in sections. ? PASl02 Compilation declaration section. different declaration Lowbound exceeds highbound The lower limit of a subrange is greater than the upper limit of the subrange, based on their ordinal values in their base type. ? PASI03 Identifier is not of appropriate class The identifier names the wrong class of data. For example, it names a constant where the syntax of the statement requires a procedure. ? PAS104 Identifier not declared The program uses an identifier that has not been declared. A-6 PASCAL MESSAGES ? PASIOS Sign not allowed A plus or minus sign was found nonnumeric type. ? PASI06 in front of an expression of Identifier previously used in this block. You gave two items the same identifier within the same block. ? PASI07 Incompatible sub range types The subrange types are not compatible according to the type compatibility. ? PASIOS of File not allowed in variant part A file type cannot appear in the variant part of a ? PASI09 rules record. Type must not be real or double You cannot specify a rea] value here. Real values cannot be used as array subscripts, control values for FOR loops, tag fields of variant records, elements of set expressions, or houndaries of subrange types. ? PASIIO Tagfield type must be scalar or subrange The tag field for a variant record must be a scalar type. ? PASlll field are compatible of incompatible types. according to the general Index type must not be real or double Array subscripts cannot be real values; integer or integer subrange values. ? PASll3 subrange Incompatible with tagfield type The case label and the tag These two items must be compatibility rules. ? PASll2 or if numeric, they must be Index type must be scalar or sub range Array subscripts must be scalar or subrange values, and cannot be of a structured type. ? PASl14 Base type must not be real or double The base type of this set or subrange cannot be one of types. ? PASllS real Base type must be scalar or subrange The base type of this set or subrange must be scalar or values, and cannot be of structured type. ? PASll6 the subrange Actual parameter must be a set of correct size The actual parameter must be of correct size when passed as a VAR parameter. ? PASl17 Undefined forward reference in type declaration: Compilation aborted. A-7 name PASCAL MESSAGES ? PASll8 Value injtializatjon must be in main program A VALUE initialization must be in the main program. ? PASl19 Forward declared: repetition of parameter list not allowed You cannot repeat the parameter declaration of a subprogram. ? PAS120 list after forward the Function result type must be scalar, subrange, or pointer The function specifies a result that is not a scalar, subrange, or pointer type. Function results cannot be structured types. ? P~S121 File value parameter not allowed A file cannot be passed as a value parameter. ? PAS122 Forward declared function: allowed repetition of result type not The result of the function appears in both the forward declaration and in the later complete declaration. Th€ result can appear only in the forward declaration. ? PAS123 Missing result type in function declaration The functjon heading does not declare the type of the the function. ? PASl24 of Fraction format for real and double only You can specify two integers in the field width (such for real, single, and double values only. ? PAS125 result as R:3:2) Error in type of predefined function parameter A parameter passed to a predefinen function is not of the correct type. ? PAS126 Number of parameters does not agree with declaration The number of actual parameters passed to the subprogram is different from the number of formal parameters declared for that subprogram. You cannot add or omit parameters. ? PAS127 Parameter cannot be element of a packed structure You cannot subprogram; use it. pass you one element of a packed structure to a must pass the entire structure if you want to ? PAS128 Result type of actual function parameter does not agree with declaration The result of an actual function parameter is specified in the formal parameter list. ? PAS129 not of the type Operands are of incompatible types Two or more of the operands in an expression are of incompatible types. For example, the program attempted to compare a numeric and a character variable. A-8 PASCAL MESSAGES ? PAS130 Expression is not of set type The operators you specified are valid only for set expressions. ? PAS131 Type of variable is not set The statement syntax requires a set variable. ? PAS132 Strict inclusion not allowed You must use the <= and >= operators to test set inclusion. PASCAL does not allow you to use the less than «) and greater than (» signs for this purpose. ? PASl33 File comparison not allowed Relational operators cannot be applied to file variables. ? PASl34 Illegal type of operand(s) You cannot perform the specified operation on data items specified types. ? PAS135 of the Type of operand must be Boolean This operation requires a Boolean operand. ? PAS136 Set element must be scalar or subrange The elements of a set must be scalar or subrange cannot have elements of structured types. ? PASl37 types. Sets Set element types not compatible The elements of this set are not all of the same type. ? PASl38 Type of variable is not an array A variable that is not an array type is followed by a left square bracket or a comma inside square brackets. ? PASl39 Index type is not compatible with declaration The specified array subscript is not specified in the array definition. ? PAS140 compatible with the type Type of variable is not record A period appears following a variable that is not a record type. ? PASl41 Type of variable must be file or pointer A circumflex character appears after the name of a variable is not a file pointer. ? PASl42 that Illegal parameter substitution The type of an actual parameter is not compatible with of the corresponding formal parameter. A-9 the type P~SCAL MESS~GES ? PAS143 Loop control variable must be an point scalar unstructured an integer, integer it cannot be a real The control variable in a FOR loop must be subrange, or user-defined scalar type; variable. ? PAS145 Type conflict between control variable and loop bounds The type of the control variable in a FOR loop with the type of the bounds you specified. ? PAS146 is incompatible Assignment of files not allowea You cannot assign one file to another. used to give values to files. ? PAS147 non-floating Output procedures must be Label type incompatible with selecting expression The type of case label Is incompatible with the type to which the selecting expression evaluates. Case labels and selecting expressions must be of compatible types. ? PAS148 Subrange bounds must be sca]ar You can specify subranges of scalar specify a real or string subrange. types only. You The index type of a nonconformant array although it can be an integer subrange. cannot be integer, You cannot assign a value to an external or predeclared identifier. function ? PAS149 ? PAS150 ? PAS151 Index type must not be integer Assignment to this function is not allowed Assignment to formal function parameter not allowed You cannot assign a value parameter. ? PAS152 to the name of a formal function No such field in this record You attempted to access a record by an incorrect field name. ? PAS153 cannot or nonexistent Type of parameter must be character string (array of char) The actual parameter passed to this function or procedure must be a character string. ? PAS154 Type of parameter must be integer The actual parameter passed to this function or procedure must be an integer. ? PAS155 Recursive %INCLUDE not allowed. ? PAS156 Multidefined case label Compilation aborted. The same case label refers to more than one statement. label can be used only once within the CASE statement. A-IO Each case PASCAL MESSAGES ? PAS157 Case label range exceeds 1000 The range of ordinal values between the largest and smallest case labels must not exceed 1000. ? PASl58 Missing corresponding variant declaration In a call to NEW or DISPOSE, more tagfield constants were specified than the number of nested variants in the record type to which the pointer refers. ? PAS159 Double, real or string tagfields not allowed Tag fields cannot be scalar. ? PAS160 real or string variables, but be Previous declaration was not forward The reiteration of a procedure or function that was declared is illegal. ? PASJGl must not forward Procedure/function has already been forward declared The subprogram has already been forward declared. ? PAS162 Undeclared procedure or function: name Compilation aborted. You specified a procedure or function without declaring it in the declaration section. ? PAS163 Type of parameter must be real or integer The subprogram parameter. ? PAS164 requires a real or integer expression as a This procedure/function cannot be actual parameter The specified predeclared procedure or function cannot be an actual parameter. If you must use it in the subprogram, cal] it directly. ? PAS165 Multiply defined label A label appears in front of more than one statement in executable section. ? PASl66 a single Multiply declared label The program declares the same label more than once. ? PASl67 Undeclared label The program contains a label that has not been declared. ? PAS168 Undefined label: label number Compilation aborted. You specified a label as an argument to the GOTO the label is not defined. ? PASl69 statement, but 0 and Set element value must not exceed 255 The ordinal value of an element of a set must be 255. A-II between PASCAL MESSAGES ? PAS170 Value parameter expected A subprogram that is passeo as nn actual parameter can have value parameters. ? PAS17l Type of variable must be textfiJe (file of char) The specified operation or subprogrnm variable as an operand or parameter. ? PASl72 Undeclared external file: You specified nn external file declaration section. ? PASl73 only requires a text file name Compilation aborted. that was not declared in the Negative set elements not allowed The valu€ of an integer set element must be between 0 and 255. ? PASl74 Parameter must be a file type The specified subprogram requires a file as a parameter. ? PAS175 "INPUT" not declared as nn external file The program makes an implicit reference to the file variable INPUT, but INPUT is either not declared or has been redeclared at an inner level. ? PAS176 "OUTPUT" not declared as an external file The program makes an impJicit reference to the file variable OUTPUT, but OUTPUT is either not declared or has been redeclared at an inner level. ? PAS177 Assignment to function identifier not allowed here Assignment to a function jdentifier is allowed function block. ? PAS178 within the Multidefined record variant A constant tag fieJd value appears definition of a record variant. ? PAS179 only more than once in the File of file type not allowed You cannot declare a file that has components of a file type. ? PAS181 Array bounds too large The bounds of an array are too large to allow the elements of the array to be accessed correctly. ? PASl82 Expression must be scalar The expression must specify a scalar value; are not legal. structured variables ? PAS183 "[GLOBAL]" or "[FORTRAN]" may only precede level 1 declarations The words (GLOBALl or [FORTRAN] can be placed only in a or procedure heading. A-12 at function PASCAL MESSAGES ? PAS184 External procedure has same name as main program Program and procedure names must be unique. ? PAS186 Formal procedures may not have conformant array parameters You cannot pass a conformant array as a parameter to a that is itself passed as a parameter. ? PASl87 IJlegal conformant array assignment The program attempts to perform an illegal conformant arrays. ? PAS188 procedure assignment involving Parameter must be scalar and not real or double The parameters to the predeclared functions sucr and PRED must be scalar types, and cannot be one of the real types. ? PAS189 Actual parameter must be a variable When you use VAR with a formal parameter, the corresponding actual parameter must be a variable and not a general expression. ? PAS190 "READLN" , textfiles "WRITELN" and "PAGE" are defined only fo r The predeclared procedures READLN, WRITELN, and PAGE operate only on text files. ? PAS191 "READ" and "WRITE" require input/output parameter list The READ and WRITE procedures require you cannot omit the parameter list. ? PASl92 at least one parameter; Illegal type of input/output parameter Arrays, sets, records, and pointers cannot be parameters READ and WRITE procedures. ? PAS193 to the Field width parameter must be of type integer The field width you specify must be an integer. ? PAS194 Variable must be of type PACKED ARRAYfl .• ll] OF CHAR The DATE and TIME procedures require a parameter of PACKED [ 1 .. 11] OF CHAR. ? PAS195 ARRAY Type of variable must be pointer The statement syntax requires a variable of pointer type. ? PAS196 Type of constant does not agree with tagfield type The type of a constant in a tag value list is the tag field type. ? PASI97 incompatible with Type of parameter must be real or double The statement syntax precision) value. requires A-I] a real (singIe- or double- PASCAL MESSAGES ? PAS198 Type of parameter must be double The statement syntax requires ? PAS199 ~ double-precision value. Parameter must be of numeric type The procedure or function requires value. ? PAS200 an integer or real number Parameter must be scalar or pointer and not real The procedure or function requires an integer, user-defined scalar, Boolean, integer subrange, user-defined scalar subrange, or pointer parameter. ? PAS201 Error in real constant: digit expected A real constant contains a nonnumeric character where is required. ? PAS202 a numeral String constant must not exceed source 1ine The end of the Jine occurs before the apostrophe that closes a string. Make sure that the second apostrophe has not been left out. ? PAS201 Integer constant exceeds range An integer constant is outside the permitted (that is, 2**31 to 2**31). ? PAS204 of integers Actual parameter is not correct type The actual parameter is not corresponding formal parameter. ? PAS205 range compatible in type with the Zero length string not allowed You cannot specify a string that has no characters. ? PAS206 Illegal digit in binary, octal or hexdecimal constant A binary, octal, or digit. ? PAS207 hexadecimal constant contains an illegal Real or double constant out of range A singleor double-precision real number is outside the permitted range 0.29*10**(-38) to 1.7*(10**38) for positive numbers and -0.29*10**(-38) to -1.7*(10**38) for negative numbers. ? PAS208 Data type cannot be initialized This variable contains a type, such as a initialized. ? PAS209 file, that cannot be Variable has been previously initialized You can specify only one VALUE declaration for a variable. ? PAS2l0 Variable is not array or record type The VALUE initialization for a variable that is not a an array contains a constructor. A-14 record or PASCAL MESSAGES ? PAS?II Incorrect number of values for this variable The VALUE declaration contains too many or too few values for the variable being initialized. ? PAS21? Repetition factor must be positive integer constant The repetition factor in an positive integer constant. ? PAS2I1 array initialization must be a Type identifier does not match type of variable The optional type identifier must be compatible with the t:"?e variable to be injtialized. ? PAS2I4 of Incorrect type of value element A constant appearing in a VALUE initialization has a type other than that of the variable, record field, or array element to be initialized. ? PAS2l5 RMS record size must be a positive integer constant The record size specified in the OPEN procedure call positive integer constant. ? PAS216 "OLD" was not a is not allowed for this file You cannot specify OLD for an internal file. ? PAS217 Assignment to Conformant Array Index is not allowed You cannot make this assignment to a conformant array index. ? PAS2I8 Array must be unpacked An array parameter to PACK or UNPACK is not unpacked correctly. ? PAS2I9 Array must be packed An array parameter to PACK or UNPACK is not packed correctly. ? PAS220 Packed bounds must not exceed unpacked bounds The bounds of the packed array exceed the unpacked bounds. ? PAS224 "rOVERLAID1" expected The statement syntax requires the keyword ? PAS225 rOVERLAID]. Illegal file attribute specification You specified an attribute in the recognized by the compiler. OPEN statement ? PAS226 Positional parameter not allowed after first parameter ? PAS227 that is non-posjtional "OLD n , "NEW", nREADONLY", or "UNKNOWN" expected The statement syntax requires either the keyword OLD or NEW. A-I5 not PASCAL MESSAGES ? PAS228 "SEQUENTIAL" or "DIRECT" expected The statement syntax requires either the DIRECT. ? PAS229 keyword SEQUENTIAL "FIXED or "VARIABLE" expected The statement VARIABLE. syntax ? PAS230 "NOCARRIAGE", expected requires "NONE", either "CARRIAGE", the keyword "FORTRAN", The statement syntax requires one of the following NOCARRIAGE, NONE, CARRIAGE, FORTRAN, or LIST. ? PAS231 or FIXED or "LIST" or keywords: II legal keyword This keyword cannot be specified in this context. ? PAS232 Parameter has already been specified You have specified the same parameter twice. ? PAS233 File variable must be specified You forgot to specify the file variable. ? PAS234 Identifier or character string literal expected You need to specify a ? PAS235 identifier or character string literal. Parameter cannot be specified in this posjtion You specified a parameter that did not belong in this place. ? PAS237 A "NEW" and "DIRECT" file must have fixed-length records You specified variable-length records for a file that fixed-length records. ? PAS238 must have Record type may not be "VARIABLE" for "DIRECT" files You cannot have variable length records for a DIRECT file. ? PAS239 %INCLUDE file not found. Compilation aborted. ? PAS240 Include/Exclude file error. ? PAS250 Too many nested scopes of identifiers CompiJation aborted. You can have only 20 levels of nesting. occurs with each block or WITH statement. ? PAS251 A new nesting level Too many nested procedures and/or functions Subprograms can be nested no more that 20 levels deep. ? PAS252 Assignment to function scope conflict not allowed here. Probable A function is nested within a function with the same name. A-l{) name PASCAL MESSAGES ? PAS253 Too many arguments in an "OPEN" statement You specified too many arguments. ? PAS255 Too many errors on this source line The PASCAL compiler diagnoses only the first 20 source line. on each The expression is too deeply nested. To correct this error, should separately evaluate some parts of the expression. you ? PAS259 ? PAS261 errors Expression too complicated Declarations out of order or repeated declaration sections The declarations must be in the following order: constants, types, variables, values, and subprograms. main program can contain value declarations. ? PAS2~4 Only routines You cannot routines. ? PAS265 "VAR" parameters specify value allowed for parameters for labels, Only the "rFORTRAN1" declared rFORTRANl declared Parameter not allowed for " [FORTRAN1" declared routines This type of parameter is routines. ? PAS266 Conformant part of dimension packed not allowed Conformant for arrays rFORTRAN] can have declared on]y one You packed more than one dimension in a conformant array part. ? PAS267 Conformant arrays must be of the same type When using relational operators with conformant arrays, the array types must be equivalent. ? PAS300 Division by zero The program attempts to divide by zero. ? PAS302 Index expression out of bounds The value of the expression is out of range for the array element to which you are assisning it. ? PAS303 Value to be assigned is out of bounds The value to the right of the assignment operator is out of range for the variable to which it is being assigned. ? PAS304 Set element expression out of range The value of the expression is out of range for the to which you are assigning it. ? PAS30S Field width must be greater than zero. A-17 set element PASCAL MESSAGES ? PAS306 Index type of conformant array parameter declaration exceeds range The index type of the actual conformant array parameter beyond the range declared in the formal parameter list. ? PAS307 of extends Modulus with zero or negative value The program tried to take the mod of zero. ? PAS309 Variable space (octal) ? PAS310 exceeds low segment memory size, Code space exceeds available address space, 777777 377777 (octal) Compile-Time Warnings % PAS401 Identifier exceeds, 31, characters Identifiers can be any length, but PASCAL scans only the first 31 characters for uniqueness. % PAS402 Error in option specification A compiler option is incorrectly specified in the source code. % PAS403 Source input after "END." ignored The compiler ignores any characters after the END that terminates the program. % PAS404 Duplicate external procedure name Two external procedures or functions have been declared with the same name. They refer to the same externally compiled subprogram. % PAS405 LABEL declaration in MODULE ignored The compiler ignores label declarations at the outermost level in a module. % PAS407 Illegal option on include file specification; LIST assumed You specified an option that is not available. % PAS408 One or more parameter values assumed before "param" % PAS409 Alternative ordering of HISTORY and RECORDLENGTH parameters % PAS4I0 Parameter type is not known by FORTRAN. % PAS413 Case label out of range % PAS450 % PAS451 % PAS452 % PAS453 % PAS454 % PAS455 % PAS456 Nonstandard Nonstandard Nonstandard Nonstandard Nonstandard Nonstandard Nonstandard PASCAL: PASCAL: PASCAL: PASCAL: PASCAL: PASCAL: PASCAL~ Exponentiation VALUE declaration OTHERWISE clause %INCLUDE directive MODULE declaration Label exceeds 9999 "$" or "" in identifier A-I8 PASCAL MESSAGES % PAS457 Nonstandard PASCAL: % PAS458 % PAS459 % PAS460 % PAS461 % PAS4fi2 Nonstandard Nonstandard Nonstandard Nonstandard Nonstandard PASCAL: PASCAL: PASCAL: PASCAL: PASCAL: % PAS463 % PAS4fi4 % PAS465 % PAS466 Nonstandard Nonstandard Nonstandard Nonstandard PASCAL: PASCAL: PASCAL: PASCAL: % PAS467 % PAS468 NonstAndard PASCAL: Nonstandard PASCAL: % PAS469 % PAS470 Nonstandard PASCAL: Nonstandard PASCAL: % PAS4 7 1 Nonstandard PASCAL: % PAS472 Nonstandard PASCAL: % PAS473 % PAS474 Nonstandard PASCAL: Nonstandard PASCAL: % PAS475 % PAS476 Nonstandard PASCAL: Nonstandard PASCAL: % PAS477 Nonstandard PASCAL: % PAS478 % PAS479 Nonstandard PASCAL: Nonstandard PASCAL: % PAS480 % PAS481 Nonstandard PASCAL: Nonstandard PASCAL: Conformant passed to value conformant array Directive "rGLOBAL)" or "rFORTRAN) " Binary, octal or hexadecimal constant Double precision constant External procedure declaration Binary, octal or hexadecima] data output Output of user-defined scalar Input of string or user-defined scalar Input/output of double precision data Implementation-defined type, function, or procedure Directive " [OVERLAIDl" Formal and actual parameters not of identical type Control variable is not local Formal and actual parameters not both packed or unpacked No parameter list declared for this call No parameter list declared for this fo rma t Nonstandard parameter declaration Array or record types not identical in assignment Types not identical in comparison VAR parameter is selector of variant record Parameter is pre-defined procedure or function NIL used as constant identifier Case constants do not cover range of tag- type Input/output of conformant string Comparison of conformant strings A-19 APPENDIX B ASCII CHARACTER SET Table B-1: The ASCIl Character Set -----------------------------------------ASCII Character Meaning NUL SOH STX ETX EOT ENQ ACK BEL BS HT LF Null Start of heading End of text End of text End of transmission Enquiry Acknowledgement Bell Backspace Horizontal tab Line feed vertical tab Form feed Carriage return Shift out Shift in Data link escape Device control 1 Device control 2 Device control 3 Device control 4 Negative acknowledgement Synchronous idle End of transmission block Cance] End of med i urn Substitute Escape File separntor Group separator Record separator Unit separator Spac '9 or blank Exc]amation mark Quotation mark Number sign Dollar sign Percent sign Ampersand Apostrophe Left parenthesis Decimal Number o 1 2 3 4 5 6 7 R 9 10 11 V1: I? FF' 13 CH SO S1 DLE DC1 DC2 DC3 1<1 15 16 17 18 19 20 DC4 21 22 23 Nl\K 24 Cl~N 25 26 27 28 29 E~1 30 31 3~ SYN ETB SUB ESC FS GS RS US SP 33 34 " 35 i 36 37 38 39 40 $ % % B-1 ASCII CHARACTER SET Table 8-1: The ASCII Decimal Number ~SCII Character 41 42 43 44 45 * + 4fi 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 Character Set (Cont.) / 0 1 2 3 4 5 f) 7 8 9 < 62 > 63 64 65 66 67 fi8 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 ? @ A 8 C D E F G H I J K L M N 0 P Q R S T U V W X y Z [ or or Meaning Right parenthesis Asterisk Plus sign Comma Minus sign or hyphen Period or decimal point Slash Zero One Two Three Four Five Six Seven Eight Nine Colon Semicolon Left angle bracket Equal sign Right angle bracket Question mark At sign Upper case A Upper case 8 Upper case C Upper case D Upper case E Upper case F upper case G upper case H Upper case I Upper case J Upper case K Upper case L Upper case M Upper case N Upper case 0 Upper case P Upper case Q Upper case R Upper case S upper case T Upper case U Upper case V Upper case W Upper case X Upper case Y Upper case Z Left squa re b racke t Back slash Right square bracket Circumflex or up arrow Back arrow 0 r underscore B-2 ASCII CHARACTER SET Table B-1: The ASCII Character Set (Cont.) ASCII Decimal Number 96 97 98 99 100 101 102 103 104 Character Meanjtng accent Lowe l~ case a Lowe l~ case b Lower case c Lower case d Lower case e Lower case f Lower case 9 Lower case h Lower case i Lower case j Lower case k Lower case 1. Lowe l~ case m Lower case n Lower case 0 Lower case p Lower case q Lower case r Lower case s Lower,case t Lower case u Lower case v Lower case w Lower case x Lower case y Lower case z Left brace Vertilcal line Right brace GraVE~ a b c d e f 9 h lOS 106 107 108 109 110 k 1 m III 0 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 P q r s t u v w j n x y z { I } Ti1dE~ DEL Delete B-3 APPENDIX C SYNTAX SUMMARY This appendix summarizes the syntAx of the PASCAL-20 language Backus-Naur Form (BNF): C.l in the BACKUS-NAUR FORM In the BNF, each element of the language is defined recursively in terms of simpler elements. The element being defined is written to the left of the symbol: ::= and its definition is writt.en to the right of tha t symbol. The BNF uses a group of metasymbols that differ from the conventions used in the rest of this manual and are not part of the PASCAL language. Table C-l ] ists the meta-symbols used in the BNF. Table C-l: BNF MetaSymbols Symbol Meaning ------------------------------------------------------------------separates the definition. < > element being defined from its Encloses a definable language element. Encloses an optional element. Means "or"; separates possible elements. Encloses elements that may be repeated one or more times, but need not be present The remainder of this section lists PASCAL in BNF. <compilation unit> ::= <program> <module> I <module> <module heading> <global declaration part> <procedure and function declaration part> END . ""= <program> ::= <program heading> <block> • <module heading> ::= <module word> <identifier> <module word> <identifier> ( <program parameters> C-l SYNTAX SUMMARY <global declaration part> ::= <label decJaration part> <constant definition part> <type definition part> <variable declaration part> <module word> ::= MODULE I r rOVERLAJDll MODULE <program heading> ::= <program word> <identifier> <program word> <identifier> ( <program param'2ters> <program parameters> ::= <external file identifier> { , <external file identifier> } <external file identifier> ::= <identifier> <program word> ::= PROGRAM r rOVERLAIDll PROGRA~ I S} <identifier> ::= <identifier head> {<Jetter or digit> <identifier head> . -= <Jetter> <letter> . -= I C I P b I c 0 I p A B N 0 a n <digit> : :=,0 I I D Q E R d e r g $ I I f I s I F S I 2 I 3 I 4 I 5 I fi I I I V h I u I v G T H U g t I 7 I ,} I K I W I X I j I k I w I x I I I I L I M Y I z I I m y I z I 8 I 9 <special symbol> ::= <operator symbol> I <reserved word> <semireserved word> I <incJude symbol> <operator symbol> - -= + I - I * I / I ) I r I 1 I '@ " I ** I = I <> I < I > I <= I >= I } I := I _ I , I I: I (* I * ) , (. , • ) 1 <reserved word> - -= DIV , MOD I NIL IN OR I AND I NOT I IF THEN I ELSE I CASE I OF I REPEAT I UNTIL I WHILE DO I FOR , TO I DOWNTO I BEGIN I END I WITH , GOTO CONST I VAR , TYPE I ARRAY I RECORD I SET , FILE FUNCTION I PROCEDURE I LABEL I PACKED I PROGRAM <semireserved word> ::= REM I OTHERWISE I MODULE VALUE <include symbol> ::= %INCLUDE <blank> ::= <single blank> { <single blank> <single blank> ::= <space character> I <tab character> <block> ::= <declaration part> <value initialization part> <procedure and function declaration part> <statement part> <declaration part> ::= <label declaration part> <constant declaration part> <type declaration part> <variable declaration part> <label declaration part> ::= <empty> I LABEL <Jabel> { , <label> } ; <label> ::= <unsigned integer> <constant definition part> ::= <empty> I CONST <constant definition> { ; <constant definition> } <constant definition> ::= <identifier> = <constant> C-2 SYNTAX Sm1MARY <constant> <unsigned number> I <sign> <unsigneo number> I <constant identifier> I <sign> <constant identifier> <string> I NIL ::= <unsigned number> ::= <unsigneo inteqer> I <unsigned real> <radix integer> <unsigned integer> ::= <digit sequence> <radix integer> - . = % <octal integer) I % <hex integer> I % <binary integer> <octal integer> <JettE!r 0> :.= ' <octa] digit sequence> ' <letter 0> ::= 0 1 0 <octal digit sequence> ::= <octal digit> { <octal digit> } <octal digit> - -= 0 I 1 I 2 I 3 <hex integer> - -= <letter x> <letter x> ::= X I 4 I 5 I h I 7 ' <hex ("iigit sequence> ' I x <hex digit sequence> ::= <hex digit> { <hex djgit> } <hex digit> - -= <digit> I A I B I I elf C I DIE I F I a I b I c I d <binary integer> "-= <letter b> ' <binary digit sequence> ' <letter b> ::= B 1 b <binary digit sequence> - ,,= <binary digit> { <binary digit> } < bin a r y dig it> :: == 0 I 1 <unsigned real> ::= <unsigned single> I <unsigned double> <unsigned single> ::= <digit sequence> • <digit sequence> <digit sequence> • <digit sequence> E <scale factor> <digit sequence> • <digit sequence> e <scale factor> <digit sequence> E <scale factor> I <digit sequence> e <scale factor> <unsigned double> ::= <digit factor> I <digit factor> I <digit <digit sequence> <digit .sequence> ::= <digit> sequence> • <digit sequence> D <scale sequenc.e> • <digit sequence> d <scale sequence> D <scale factor> I d <scale factor> <digit> } <scale factor> ::= <digit sequence> I <sign> <digit sequence> <s ig n> :: = + I <constant identifier> ::= <identifier> <string> ::= , <character> { <character> } , <character> ::= <any ASCII character except '> I <type definition part> <empty> TYPE (type definition> I' 00: C-3 <type definition> } SYNTAX SUMMARY <type definition> <type> ::= ::= <identifier> <simpJe type> --= <type> I <structured type> <simple type> - -= <scalar type> <scalar type> = I <pointer type> I <subrange type> <type identifier> <identifier> { , <ioentifier> <subrange type> ::= <constant> <constant> 00 <type identifier> - -= <identifier> <structured type> - -= <unpacked structured type> PACKED <unpackeri structured type> <unpacked structured type> ::= <array type> < set type> I < f i 1 e type> I I <record type> <array type> ::= ARRAY <index type> { , <index type> } 1 OF <component type> <index type> ::= <simple type> <component type> ::= <type> <record type> ::= RECORD <field list> END <field list> ::= <fixed part> < va ria n t pa r t> I <fixed part> <fixed part> ::= <record section>{ <variant part> I <record section> } <record section> ::= <empty> I <field identifier> { , <field identifier> } : <type> <variant part> ::= CASE <tag field> <type identifier> OF <variant> { ; <variant> } <tag field> ::= <field identifier> : <variant> ::= <case label list> : < empty> ( <field list> I <empty> <case label list> ::= <case label> { , <case label> } <case label> ::= <constant> <set type> ::= SET OF <base type> <base type> <file type> 00= 00= <simple type> FILE OF <type> <pointer type> ::= A <type identifier> <variable declaration part> ::= <empty> I VAR <variable declaration> { ; <variable declaration> <variable declaration> ::= <id~ntifier list> : <type> I <identifier list> : <type> := <value> <identifier list> ::= <identifier> { , <identifier> } <value initialization part> ::= VALUE <value initialization> { ; <value initialization> } ; I <empty> C-4 SYNTAX Sur~MARY <value initialization> ::= <identifier> := <value> <value> ::= <constant> I <set constant> I <constructor> r <constant element list> 1 <set constant> ::= <constant element list> ::= <empty> <constant el(~ment> { , <constant element> <constant element> ::= <constant> <constructor> ::= <opt.ional type> <constant> •• <constant> ( <value element> { i' <value element> } ) <optional type> ""= <empty> <type identifier> <value element> ""= <value> <repetition factor> OF <value> <repetition factor> ::= <unsigned integer> <constant identifier> <procedure or function declaration part.> ::= { <procedure or function declaration> <procedure or function declaration> <function declaration> ."= <procedure declaration> <procedure declaration> ::= <internal procedure declaration> <external procedure declaration> <forward procedure declaration> <internaJ procedure declaration> ::= <procedure heading> <block> rrGLOBAL]] <procedure heading> <block> [rFORTRAN]] <procedure heading> <block> <external procedure declaration> ::= <procedure heading> EXTERN I <procedure heading> EXTERNAL I <procedure heading> FORTRAN <forward procedure declaration> ::= <procedure heading> FORWARD [rGLOBAL]] <procedure heading> FORWARD I rrFORTRAN1] <procedure heading> FORWARD <procedure heading> ::= PROCEDURE <identifier> ; PROCEDURE <identifier> ( <formal pnrameter section> { ; <formal par"ameter section> } ) <formal parameter sect.ion> ::= <extended parameter group> VAR <extended parameter group> I FUNCTION <parameter group> I PROCEDURE <identifier> { , <identifier> } <procedure heading> I <function heading> <extended parameter group> ::= <parameter group> I <identifier> { , <identifier> } : <conformant array schema> <conformant array schema> ::= ARRAY r <index type specification> { ; <index tYPE! specification> } ] OF <type identifier> ARRAY ( <index type specification> { , <index type specification> } , OF <conformant array schema> PACKED ARRAY r <index type specification> 1 OF <type identifier> <index type specification> ::= <identifier> •• <identifier> <scalar type identifier> C-5 SYNT.AX SUMMARY <scalar type identifier> ::= <parameter group> <i~entifier> <identifier> ::= , <identifi.er> <type identifier> <function declaration> - -= <internal function declaration> <external function declaration> <forward function declaration> <internal function declaration> ::= <function heading> <block> rGLOBAL) <function heading> <block> rFORTRANl <function heading> <block> <external function declaration> ::= <function heading> EXTERN I <function heading> EXTERNAL I <function heading> FORTRAN <forward function declaration> ::= <function heading> FORWARD I rGLOBALl <function heading> FORWARD I rFORTRANl <function heading> FORWARD <function heading> - -= FUNCTION <identifier> : <result type> ; FUNCTION <identifier> ( formal parameter section> { ; <forma] parameter section> } ) : <result type> <result type> ::= <type identifier> <statement part> <statement> ::= ::= <compound statement> <unlabeJ ed statement> I <label> : <unlabeled statement> <unlabeled statement> ::= <simple statement> <structured statement> <simple statement> ::= <assignment statement> <go to statement> <procedure statement> I <empty statement> <assignment statement> - -= <variable> := <expression> <function identifier> := <expression> <variable> - -= <entire variable> I <component variable> <referenced variable> <entire variable> ::= <variable identifier> <variable identifier> ::= <identifier> <component variable> ::= <indexed variable> I <field designator> <file buffer> <indexed variable> - -= <array variable> r <expression> { , <expression> } ] <array variable> ::= <field designator> <variable> ::= <record variable> • <field identifier> <record variable> ::= <variable> <field identifier> ::= <identifier> <file buffer> ::= <file variable> <file variable> ::= A <variable> C-6 I SU~1MARY SYNTAX <referenced variable> ::= <pointer variable> ft <pointer variable> ::= <variable> <expression> ::= (simple expression> I <simple expression> <relational operator> <simple expression> <relational operator> ::= = I <> I < I <= I >= > I lN <simple expression> ::= <term> <sign> <term> <simple expression> <adding operator> <term> <adding operator> ::= + I - I OR <term> <multiplying operator> <primary> <term> ::= <primary> <multiplying operator> ::= <primary> ::= <factor> * I / I DIV I MOD I AND I <primary> REM ** <factor> <factor> ::= <vari.able> I <unsigned constant> I ( <expression> ) <function designator> I <set> NOT <factor> <unsigned constant> - -= <unsigned number> <string> <constant identifier> I NIL <function designator> - -= <function identifier> <function identifier> ( <actual parameter> { , <actual parameter> } ) < fun c t ion ide n t i fie r> - - = < ide n t i fie r> <set> ::= [ <elemE~nt list> ] <element list> : :== <element> { , <el.~ment> } I <empty> <element> ::= <expression> I <expression> ._ <expression> <procedure statement> ::= <procedure identifier> <procedure identifier> ( <actual parameter> { , <actual parameter> } ) <procedure identifier> ::= <identifier> <actual parameter) - -= <expression> I <procedure identifier> I <function identifier> <go to statement> ::= GOTO <label> <empty statement> ::= <empty> <empty> :: = <structured statement> ::= <compound statement> I <conditional statement> I <repetitive statement> I <with statement) <compound statement> ::= BEGIN <statement> ; <statement> } END <conditional statement> ::= <if statement> <case statement> <if statement> IF <expression> THEN <statement> I IF <expression> THEN <statement> ELSE <statement> ::~ C-7 ~YNTA.X SUMMARY <case statement> ::= CASE <expression> OF <case list element> f ; <case list element> } <otherwise part> <end case> <case list element> ::= <case 1abel ] ist> : <statement'> <otherwise part> ::= <empty> OTHERWISE <statement,> { ; OTHERWISE <statement> < end case> :: = END I < empty> <statement> J ; <sta tement> END <repetitive statement> - -= <while statement> I <repeat statement> <for statement> <while statement> ::= WHILE <expression> DO <statement> <repeat statement> ::= REPEAT <statement,> { ; <statement> UNTIL <expression> <for statement> ::= FOR <control variable> := <for list> DO <statement> <for list> ::= <initial value> TO <final value> <initial value> DOWNTO <final value> <control variable> ::= <identifier> <initial value> ::= <expression> <final value> ::= <expression> <with statement> ::= WITH <record variable list> DO <statement> <record variable list> ::= <record variable> { , <record variable> <open statement> ::= OPEN ( <open parameters> <open parameters> ::= <file parameters> I <keyword parameters> { , <keyword parameters> <keyword parameters> - -= FILE VARIABLE := <file variable> T FILE NAME := <file name> I HISTORY := <file status> I RECORD LENGTH := <record length> I ACCESS-METHOD := <record access mode> I RECORD-TYPE := <record type> I CARRIAGE CONTROL := <carriage control> <file name> ::= <variable> <constant identifier> I I <file specification> ' <file status> ::= OLD I NEW I UNKNOWN I READONLY <record length> ::= <unsigned integer> <record access mode> ::= SEQUENTIAL I DIRECT <record type> ::= VARIABLE I FIXED <carriage control> ::= CARRIAGE I NOCARRIAGE I LIST C-8 SYNTAX SUr-1MARY <file parameters> ""= <file variable> <RMS file specification> <RMS fiJe history> <RMS record length> <RMS record access mode> <RMS record type> <RMS cRrriage control> <RMS file specification> ::= , , <file specification> ' <RMS record length> ::= , <record length> <RMS file history> < file status> ""= <RMS record access mode> <RMS record type> ::= , ."= I <empty> I <empty> <record access mode> <record type> C-9 I <empty> I <empty> I <empty> APPENDIX D SUMMARY OF PASCAL-20 EXTENSIONS TO PROPOSED ISO STANDARD Category Extension Lexical and syntactical Semi reserved words: REM MODULE, OTHERWISE, Exponentiation operator (**) REM operator Binary, hexadecimal, and octal for integers notation Double-precision real data type Dollar sign ($) and underscore characters in identifiers () Identifiers of up to 31 characters Predefined types SINGLE, DOUBLE Predeclared Procedures CLOSE, DATE, FIND, HALT, OPEN, TIME, MARK, RELEASE READ, READLN, WRITE, and WRITELN extensions Parameters of character string and enumerated types for READ and READLN LINELIMIT, Parameters of enumerated types for WRITE and WRITELN READ, READLN, WRITE, and WRITELN extensions Optional carriage-control specification for text files with WRITE and WRITELN Declarations variable initialization Statements OTHERWISE clause in CASE statement Procedures and Functions External procedure declar,ation and function Support for calling externally declared FORTRAN subroutines and for declaration of PASCAL subroutines that can be called by FOR'TRAN Compilation MODULE capability for combining declarations and definitions to be compiled independently from the main progralltl D-I -------- - - - - ---- ------------------- APPENDIX E ISO COMPLIANCE This appendix is a statement of the compliance of PASCAL-20 with PASCAL standard ISO 7185. It is divided into four -sections: the 1. Implementation-defined features. This is a list of the features of PASCAL that must be defined by each implementation, but which may vary between implementations. 2. Implementation-dependent features. This is a list of the features of PASCAL which mayor may not be defined by an impl emen ta tion. 3. Errors. This is an explanation of how PASCAL-20 handles each of the errors defined by ISO 7185. 4. Exceptions and restrictions. This is a list of violations of the standard which PA$CAL-20 does not detect, and restrictions imposed by PASCAL-20. This appendix does not list extensions to the ISO 7185 standard implemented by PASCAL-20. These extensions are listed in Appendix D. E.1 IMPLEMENTATION-DEFINED FEATURES The ISO 7185 standard leaves the exact definition of a number of language elements up to the implementation. Following is a list of those features, and the definition given them by PASCAL-20. 1. The predefined type charact€!r set. CHAR 2. The identifier MAXINT denotes a value of 2**35-1, the maximum integer value of a PDP-lO word. 3. In a WRITE or WRITELN statement, the default field-width for integers is 10, for real numbers is 16, and for Booleans is 16. The number of digits written in the exponent of a floating-point format real is 2. On output to a text file, the Boolean values TRUE and FALSE are translated to the uppercase character strings "TRUE" and "FALSE" respectively. E-l corresponds to the 7-bit ASCII which is ISO COMPLIANCE 4. A program parameter that is a file variable is bound at runtime to an external (operating system) file. An external file may exist prior to execution of the program and is not deleted when the program exits. PASCAL-20 determines which file specification to use when opening the file in the following manner: • If an OPEN statement is executed prior to a RESET or REWRITE of the file, the file specification given in the OPEN statement is used. • If no OPEN statement is executed, the RESET or REWRITE looks for a logical name with the same name as the file va ria b 1 e . I f i t fin d s the ]. og i cal n arne, t ha t n arne is used as the file specification. • Otherwise, the variable name is used as and an extension of .DAT is assumed. the file name, The ISO 7185 standard also states that the precise actions of the I/O procedures REWRITE, PUT, RESET, GET, and PAGE are implementation defined. In the following items, F is assumed to be a file variable, and the various preand post assertions for each operation are assumed to be true. 1. REWRITE(F) creates or supersedes an and opens the file for writing. 2. PUT(F), where F is a text file, writes the contents of the file buffer variable to the output buffer, and advances the buffer pointer; no file operation is performed. 3. PUT (F) , where F is not a text file, writes the file buffer variable to the file. 4. RESET(F) opens an existing operating system file for reading, reads the first record, and assigns a value to the file buffer variable. 5. GET (F) , where F is a text file, advances the file input buffer pointer. If EOLN (F) is true, the next record is read from the file, and the buffer pointer is reset to the beginning of the buffer. 6. GET (F) , where F is not a text file, from the file. 7. PAGE(F) first flushes the output buffer to the file. Then, it causes the file to skip to the top of the next page; the mechanics of this depend on the setting of the file's carriage-control attribute. If this attribute is LIST (the default), a form feed character (control-L) is written to the file. If the attribute is CARRIAGE or FORTRAN, a '1' is written to the file. If the attribute is NOCARRIAGE or NONE, an error is generated. E-2 operating reads the the system file, contents next of record ISO COMPLIANCE E.2 IMPLEMENTATION-DEPENDENT FEATURES These language elements are defined by the ISO 7185 standard as "possibly differing between processors and not necessarily defined for any particular processor." Following is a description of how PASCAL-20 treats each of these elements. E.3 1. The order of evaluation of array order (t.hat is, left to right). indices is their lexical 2. The order of evaluation of members of a set constructor their lexical order (that is, left to right). 3. The order of evaluation of the operands of a dyadic operator (for example, '+') depends on the complexity of each operand. Both operands are always evaluated (even in Boolean expressions which could be "short-circuited"). 4. The order of evaluation, accessing, and binding of actual parameters to formal parameters in a procedure or function call is their lexical order (that is, left to right). 5. The varjable in an assignment statement is accessed after the evaluation of the expression. 6. The effect of reading a file at the point where a PAGE was executed when writing the file is to return either a form-feed character (control-L) or the digit '1', depending on the status of the file when the PAGE was executed. (See above for a description of PAGE's actions.) 7. Program parameters which are not file variables defined meaning in PASCAL-20, and cause an error. have is no ERROR HANDLING This section describes how the PASCAL-20 compiler and run-time system detect violations of level 1 of the standard proposed by the ISO for the PASCAL language. Errors detected at run time cause a program to terminate and return appropriate error messages. Errors described here as "not detected" cause a program to produce unexpected results. The type of an index value is not assignment compatible with the index type of an array. Explanation: Detected at run time if checking was enabled during compilation. The current variant changes while a reference to it exists. Explanation: Not detected. An example of a reference to a variant is the passing of the variant to a formal VAR parameter. IlIJ'he value of a variable to which a pointer refers (p) Explanation: Detected if checking was enabled at run time. The val ue of a va r iable to wh ich a po inter refers (p) Explanation: is NIL. Not detected. E-3 is undefined. ISO CO~PLIANCE The DISPOSE procedure is calJed to dispose of variable while a reference to the variable exists. Explanation: heap-allocated Not detected. Examples of such references are: passing the variable or a component of it to a formal VAR parameter, or using the variable in a WJTH statement (if the variable is a record). The value of file f changes while a reference to Explanation: a f~ exists. Not detected. An example of a reference to f~ is the passing of f- by reference to a routine; until the routine has ceased execution, you may not perform any operation on file f. The ordinal type of an actual parameter is not assignment with the type of the corresponding formal parameter. Explanation: compatible Detected at run time if checking was enabled during compilation of the called routine. The set type of an actual parameter is not assignment compatible the type of the corresponding formal parameter. Explanation: Detected at run time if checking was enabled during compilation of the called routine. A file is not in Generation mode when a PUT, WRITE, WRITELN, procedure is attempted. Explanation: when a PUT, WRITE, WRITELN, or PAGE WRITELN, Detected at run time. The value of the file procedure is attempted. Explanation: PAGE Detected at run time. The result of an EOF function is not TRUE when a PUT, WRITE, or PAGE procedure is attempted. Explanation: or Detected at run time. A file is in Undefined mode procedure is attempted. Explanation: with buffer variable is undefined when a PUT Not detected. A file is in Undefined mode when a RESET procedure is attempted. Explanation: Not detected. A file is not in Inspection mode when a GET, READ, or READLN procedure is attempted. Explanation: Detected at run time. A file is in Undefined mode when a GET, READ, or READLN attempted. Explanation: is Detected at run time. The result of an EOF function is TRUE when procedure is attempted. Explanation: procedure Detected at run time. E-4 a GET, READ, or READLN ISO COMPLIANCE The type of the file buffer is not assignment compatible with the type of the variable that is a parameter to a READ or READLN procedure. Explanation: Detected at run time if checking is enabled compilation at the READ or READLN. during WRITE or WRITELN The type of the expression being written by a the type of the file procedure is not assignment compatible with buffer variable. Explanation: Detected at run time if checking is enabled compilation of the WRITE or WRITELN. The current variant does not exist in the list of with the NEW procedure. Explanation: variants during specified Not detected. The DISPOSE(p) procedure is called to deallocate a pointer variable that was created using the variant form of the NEW procedure. Explanation: Not detected. specify the The variant form of the DISPOSE procedure does not disposal of the same number of variants that were created by the variant form of the NEW procedure. Explanation: Not detected. The variant form of the DISPOSE procedure does not specify the disposal of the same variants that were created by the variant form of the NEW procedure. Explanation: Not detected. The value of the parameter to the DISPOSE procedure is NIL. Explanation: Detected at run time. The value of the parameter to the DISPOSE procedure is undefined. Explanation: Usually detected at run time. A variant record created by the NEW procedure is accessed as a rather than one component at a time. Explanation: Not detected. In the PACK(a,i,z} procedure, the type of the index assignment compatible with the index of a. Explanation: when i is not the value of at least one is greater than the upper Not detected. The index value i in the PACK procedure bound of the index of a. Explanation: value Not detected. The PACK procedure is attempted component of a is undefined. Explanation: whole, Not detected. E-5 ISO COMPLIANCE In the UNPACK(z,i. ,a) procedure, the type of the index value i assignment compatible with the index type of a. Explanation: the upper the value at least one of Not detected. The resulting value of SQR(X) Explanation: than Not detected. The UNPACK procedure is attempted when component of z is undefined. Explanation: not Not detected. The inctex value i in the UNPACK procedure is greater bound of the index type of a. Explanation: is does not exist. Detected at run time. In the expression LN(X), the value of X is negative. Explanation: Detected at run time. In the expression, SQRT(X), the value of X is negative. Explanation: Detected at run time. The resulting va]ue of TRUNC(X) does not exist after the following calculations have been done: if the value of X is positive or zero, then 0 <= X-TRUNC (X) <1; otherwise, -1 < X-TRUNC (X) <= o. Explanation: The resulting calculations ROUND(X) is equivalent to Detected at run time. value of ROUND(X) does not exist after the following have been done: if the value of X is positive or zero, equivalent to TRUNC(X+O.5); otherwise, ROUND(X) is TRUNC(X-O.5). Explanation: Detected at run time. The resulting value of CHR(X) Explanation: Not detected. The resulting value of SUCC(X) Explanation: is called when the file f is undefined. Detected at run time. The function EOLN(f) Explanation: does not exist. Detected at run time if checking was enabled during compilation. The function EOF(f) Explanation: does not exist. Detected at run time if checking was enabled during compilation. The resulting value of PRED(X) Explanation: does not exist. is called when the file f is undefined. Detected at run time. E-6 ISO COMPLIANCE The function EOLN(f) Explanation: is called when the result of EOF(f) is TRUE. Detected at run time. A variable is not initialized before it is first used. Explanation: Not detected. In the expression X/Y, ExplAnation: the value of Y is zero. Detected at run time. In the expression I DIV J, Explanation: is zero. Detected at run time. In the expression T MOD J, Explanation: the value of J the value of J is zero or negative. Detected at run time if J J is negative. is zero; An operation or function involving integers does not mathematical rules for integer arithmetic. Explanation: conform to the control to Detected at run time. A function result is undefined when the function the calling block. Explanation: not detected if returns Not detected. The ordinal type of an expression is not assignment compatible with the type of the variable or function identifier to which it is assigned. Explanation: Detected at run time if checking was enabled during compilation. The set type of an expression is not assignment compatible with the type of the variable or functjon identifier to which it is assigned. Explanation: Detected at run time if checking was enabled during compilation. None of the case labels is equal in value to the case CASE statement. Explanation: selector in a Not detected. In a FOR statement, the type of the initial value is not assignment compatible with the type of the control variable, and the statement in the loop body is executed. Explanation: Detected at run time if checking was enabled during compilation. Assignment compatibility is not enforced if the statement in the loop body can never be executed. E-7 ISO COMPLIANCE In a FOR statement, thp type of the final value is not assignment compatible with the type of the control variable and the statement in the loop body is executed. Explanation: Detected at run time if checking was enabled during compilation. Assignment compatibility is not enforced if the statement in the loop body can never be executed. When an integer is being read from a text file, the ~igits read do not constitute a valid integer value. (Initial spaces and end-of-line markers are skipped.) Explanation: Detected at run time. When an integer is being read from a text file, the type of the value read is not assignment compatible with the type of the variable. Explanation: Detected at run time. When a real number is read from a text file, the digits read do not constitute a valid real number. (Initial spaces and end-of-line markers are skipped.) Explanation: Detected at run time. The value of the file buffer variable is READLN procedure is performed. Explanation: undefined when a READ or Not detected. A WRITE or WRITELN procedure specifies a field width in which the integers representing the total width and the number of fractional digits are less than 1. Explanation: Detected at run time. The bounds of an array passed to a conformant array parameter outside the range specified by the conformant array's index type. Explanation: E.4 are Not detected. EXCEPTIONS AND RESTRICTIONS PASCAL-20 is not able to detect a number of violations of the ISO 7185 standard. Violations that are not defined as errors are listed below. 1. Statements threatening a FOR-loop control variable are not detected. A statement "threatens" a variable if it occurs within the FOR-loop or within a prior procedure, and if it is one of the following kinds of statements: • A READ or READLN statement containing the variable • An assignment statement with the variable to the left of the' :=' • A procedure or function formal VAR parameter E-8 call with the variable as a ISO COMPLIANCE 2. The concept of a "totally-undefined" variable has no meaning in PASCAL-20. Any violation of the standard which requires "totally-undefined" to be meaningful is not detected. 3. Variant records in PASCAL-20 are implemented by overlaying the fields of the variants in the same memory. Changing the active variant does not alter the contents of that memory, and the fields of the newly-active variant are not undefined. Also, note that variant parts of records cannot be of the type FILE. 4. The DISPOSE procedure does not cause its argument undefined, but rather the argument is set to NIL. 5. No restrictions on the relative placement of labels and statements are enforced. 6. Packed and unpacked sets are implemented in similar ways in PASCAL-20. Therefore, the compiler is very "loose" about interchanging packed and unpacked sets; the only requirement imposed on compatibility of set types is that their base types must be compatible. 7. Under certain conditions, a procedure call may be bound to the wrong procedure definition. This can only happen when two procedures are declared with the same name at different levels, and the inner procedure is called before it is declared. The following example illustrates this situation. to become GOTO PROCEDURE B; BEGIN (* level 1 *) END; PROCEDURE C; PROCEDURE D; BEGIN B (* call bound to level 1 procedure *) END; PROCEDURE B; BEGIN (* level 2 END; BEGIN END; *) PASCAL-20 also imposes a number of restrictions are: on programs. These 1. Identifiers may be of any length, but only the first 31 characters are stored. Therefore identifiers in PASCAL-20 must be unique in the first 31 characters. 2. The ordinal values of the base type of a set type are limited to the range 0 •• 255. This means that no set may have more than 256 elements. 3. File variables are not permitted as part of a record. 4. The range of ordinal values of case statement must be less than 1000. E-9 fields in constants the variant in a CASE APPENDIX F DIFFERENCES BETWEEN PASCAL-20 AND VAX-II PASCAL PASCAL-20 VI and VAX-II PASCAL V2 are compatible languages; that is, you can compile and run a PASCAL-20 program on a VAX/VMS operating system, and you can compile and run a VAX-II PASCAL program on a TOPS-20 operating system. However, there are differences between the languages. The VAX-I] PASCAL language (V2) contains features that the PASCAL-20 language does not. Therefore, if you plan to transport PASCAL programs from the VAX/VMS operating system to the TOPS-20 operating system, you should avoid using these additional features. This appendix lists the additional features that VAX-II PASCAL (V2) has over PASCAL-20 (VI). F-l DIFFERENCES BETWEEN PASCAL-20 ~ND VAX-Il PASCAL Table F-I Jists the language eJements that VAX-II PASCAL V2 PASCAL-20 does not: Table F-I: has that Additional Language Elements Category Language Element Special Symbol Type cast operator Nonstandard Reserved words %DESCR %IMMED %STDESCR %REF VARYING Predeclared Identifiers ~DD INTERLOCKED ADDRESS BITNEXT BITSIZE CLE~R INTERLOCKED DBLE DELETE EST.~BL ISH FINDK INDEX INT LENGTH LOCATE LOWER NEXT PAD QUAD QUADTRUPLE READY RESETK Data Types UNSIGNED: a through 2**~2 - 1 o through 42949n7295 Formal Parameter List foreign section Structured Type VARYING OF CHAR Real Types G_floating QUADRUPLE String Operators Plus sign (+) Predeclared Procedures DELETE(f,e) ESTABLISH(id) FINDK(f,kn,kv,m,e) LOCATE(f,n,e) READV (s ,vI, .•• ,vn) RESTK(f,kn,e) REVERT TRUNCATE(f,e) UNLOCK ( f , e) UPDATE(f,e) WR I T EV ( s , pI, • • • , p n ) F-2 REVERT SET INTERLOCKED SIZE STATUS SUBSTR TRUNCATE UAND UFB UINT UNLOCK UNOT UNSIGNED UOR UPDATE UPPER GROUND UNTRUNC UXOR WRITEV DIFFERENCES BETWEEN PASCAL-20 AND VAX-II PASCAL Table F-I: Additional Language Elements (Cont.) - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - , , - - - -'.-- ---<"-,------- Category Language Element - - - - - - - - - - - - - - - - - - , , - - , - - - - - - - - - - - - - - - - - - - - , - - , - -, Predeclared Functions See Table F-2 OPEN Parameters Procedure DISPOSITION SHARING USER ACTION ERROR KEYED CLOSE Parameters Procedure DISPOSITION USER ACTION ERROR -'," The following predeclared procedures are contained in both PASCAL languages, however, VAX-II PASCAL offers an additional argument: e = error parameter These predeclared procedures are: FIND(f,n,e) OPEN(f,parameters,e) PAGE(f,e) PUT(f,e) READ(f,vl, ... ,vn,e) READLN(f,vl, ... ,vn,e) RESET(f,e) REWRITE(f,e) WRITE(f,pl, •.. ,pn,e) Whenever you see rfattribute-listl] in a syntax description in the VAX-Il PASCAL language, it signifies that you can add certain arguments to the syntax depending on the type of circumstances. Note the following syntax and attribute descriptions: Attribute-list ({identifier IT ( { constant-expression }, ... ) ] },.•.. ] In the PASCAL-20 language, only a PROGRAM, MODULE, PROCEDURE, or The only attribute for a PROGRAM FUNCTION can have an attribute-list. or MODULE is OVERLAID. The only attributes for a PROCEDURE or FUNCTION are GLOBAL and FORTRAN. Note that in PASCAL-20 the GLOBAL attribute can not be followed by an identifier. F-3 DIFFERENCES BETWEEN PASCAL-20 AND VAX-II Table F-2 lists additional predeclared functions provides but P~SCAL-~O does not: Table F-2: P~SCAL that PASCAL Additional Predeclared Functions Category Function Boolean UFB(f) Transfer DBLE(x) QUAD (x) UINT(x) UROUND (r) UTRUNC (r) Dynamic Allocation ADDRESS(x) Character String INDEX(sl,s2) LENGTH(s) PAD(s,fill,l) SUBSTR(s,b,l) Un signed UNAD(ul,u2) UNOT (u) UOR(ul,u2) UXOR(ul,u2) Allocation Size SIZE(x,cl, ... ,cn) NEXT (x) BITSIZE(x) BITl\JEXT (x) Low Level Interlocked ADD INTERLOCKED(e,v) SET-INTERLOCKED(b) CLEAR INTERLOCKED(b) Miscellaneous STATUS (f) If you plan to transport VAX-II PASCAL programs PASCAL-20 programs to VAX/V~1S, note the following: • VAX-II to TOPS-20, or The precision for INTEGER data type: TOPS-20 ( .- 2 * * ~ 5 ) t h r 0 ug h ( + 2 * * 3 5 ) -1 through +34359738367 -34~59738368 VAX/VMS • • (-2**31)+1 through (+2**31)-1 -2147483647 through +2147483647 The maximum number of items in an enumerated type: TOPS-20 Depends on amount of memory available VAX/VMS 65,535 PASCAL-20 has two procedures MARK and RELEASE that are used in conjunction with NEW and DISPOSE. VAX-II PASCAL does not have MARK and RELEASE. If you have any further questions concerning VAX-II PASCAL, the VAX-II PASCAL documentation set. F-4 refer to APPENDIX G PROCEDURE AND FUNCTION CALLING SEQUENCES This appendix] describes the calling sequences and conventions used by PASCAL for user-defined procedures and functions. This information is particularly useful in writing MACRO routines that interface with PASCAL programs. Note that, in this appendix, procedures and functions. explicitJy noted. G.I "procedure" refers to both the word in the case of functions are Exceptions RUN-TIME STACK The majority of ~un-time information is kept on the stack; in particular, the stack contains all local variables, parameters, static and dynamic links, and return addresses for procedure calls. The stack pointer is kept in AC 17. A frame pointer, used for most variable accessing, is kept in AC 16. The frame pointer is fixed over the course of a procedure, while the stack pointer can change. Figure G-l shows the status of the stack just after a PUSHJ to a procedure. =======~================== AC 0 -) 1111111I111111111111111111 I previous stack frame I 1111111I111111111111111111 (-- =========~==================== I I parameter values, I addresses, descriptors I I I I =======~================== I saved stack pointer )-- =======~================== ACl7 -) I caller's return addressl =======~================== Figure G-l: Status of Stack After PUSHJ The information in this appendix is Moody @ 1982. G-I copyrighted by Scott Arthur PROCEDURE AND FUNCTION CALLING SEQUENCES Figure G-2 shows the stack frame in its entirety, first executable statement in a procedure. 1111111111111111111111111I I previous stack frame I 11111111111111111111111111 parameter values, addresses, descriptors saved stack pointer I I I the procedure, the I I I I 1 )-- I I I I caller's return addressl dynamic link to prior <----<-- I ========================== AC16 -) just )----- static link function value (if a function) 2 words I local variables I 11111111111111111111111111 oversized value parameters saved ACs 2 - IS size of conformant value parameter space conformant array value parameters AC17 -) next available stack space Figure G-2: G.2 Stack Frame MECHANICS OF A PROCEDURE CALL When PASCAL generates a call to a following general sequence is followed: 1. Save the current stack 2. Push the parameters onto the Passing") • 3. Push the s~ved point~r user-defined in AC stack o. (see below, stack pointer onto the stack. G-2 "Parameter PROCEDURE AND FUNCTION CALLING SEQUENCES 4. Copy the current frame dynamic link. 5. Determine the frame pointer of the block lexically the called procedure, and copy it into AC o 6. pointer into AC O. Th i s i s enclosing This is the static link. Call the procedure by means of a PUSHJ. After the called procedure returns, the stack is restored to previous state. PASCAL expects the called procedure to preserve accumulators except ACs a and~. (Note particularly that AC 16, f ram e po i n t e r , mu s t be res tor e d . ) I n t h e cas e 0 f a f un c t ion, function value is returned in AC a (P,Cs a and 1 if the function is type DOUBLE). G.3 the its all the the of PARAMETER PASSING How a parameter is passed depends on what kind of parameter it is and, for a value parameter, how large it is. The five different methods used to pass parameters are: 1. Value parameter by value 2. Value parameter by address 3• Re fe renCE! (VAR) 4• Procedure/function parameter 5. Conformant array parameter parameter Each of these methods is described be]ow. G.3.1 Value Parameter Passed By Value A value parameter passed by value is simply pushed onto the stack. This method is used for sets, DOUBLE, and any type that fits into a single word, including integer, real, char, pointers, scalars, and small packed arrays and records. G.3.2 Value Parameter Passed By Address Any value parameter larger than one word, other than a DOUBLE or set parameter, is passed by address. The address of the parameter, without indirection or indexing, is pushed onto the stack. It is the responsibility of the called procedure to copy the parameter into its own local storage. G-3 PROCEDURE AND FUNCTION CALLING SEQUENCES G.3.3 Reference (VAR) Parameter All VAR parameters are passed by address. The address of the parameter, without indirection or indexing, is pushed onto the stack. Thus, it is perfectJy safe (and recommended) to access the contents of a VAR parameter using indirection. G.3.4 Procedure Or Function Parameter Procedures and functions, as parameters, are passed as two-word descriptors. The first word of the descriptor is the address of the procedure's entry point; the second is its static link. The static link is needed when the procedure is actually called (see above under "Mechanics of a Procedure Call"). G.3.5 Conformant Array Parameter A conformant array can be of any size; however, in order for parameters to have fixed offsets from the frame pointer, a fixed-size descriptor must be passed. This oescriptor contains a fixed part of two words, and a variabJe part of three words for each conformant dimension. The fixed part contains the base address of the array in the first word. The second word contains the overall size of the passed array in words. Each three words of the variable part contain information on one conformant dimension. The second and third words contain the lower and upper bounds, respectively, on the index of the dimension. The first word contains the size of the dimension, which is the upper bound minus the lower bound plus one. The conformant array descriptor is the same for both value and VAR parameters. It is the responsibility of the called procedure to copy value conformant parameters into its own local storage. G-4 PROCEDURE G.4 ~ND FUNCTION CALLING SEQUENCES PARAMETER ACCESSING EXAMPLE Figure G-3 gives an example of a typical external procedure declaration, followed by MACRO code showing how the various parameters can be accessed. PROCEDURE Test(first: DOUBLE; VAR second! INTEGER; third: ENTRY TE~3T TEST: MOVE 1,,"':?(1./) MOVEI 2,(~··~:·3(17) MOVE MOVE 29 .... :3(1.7) DMOVE 4, .... !}(:L7) MOVEM :'3,t~""3(17) PDP,j 1?~ Figure G-3: :3¥(~"'<3(17) INTEGER); EXTERNAL; ;Define as ~lobal symbol ;Save ACs in local stora~e ;Get value of THIRD ;Get address of SECOND ;Get address of SECOND (alternate method) ;Get value of SECOND ;Get (2-word) value of FIRST ;Perform computations iReturn new value of SECOND ; F~f?S to re ACs ;Return to caller External Procedure Declaration Saving the ACs is not shown; they are assumed to be preserved in some static locations, not on the stack. The stack pointer is used for accessing the parameters. (If the ACs are saved on the stack, or if the stack is used for other purposes, then another AC should be set up for accessing parameters.) Offset a (from AC 17) is t.he return address; offset -1 is the saved stack pointer. Therefore, offset -2 is the last parameter location. Since THIRD is an integer, it takes up only one word, and is accessed with an offset of -2. The next previous parameter, SECOND, is a VAR parameter, passed by address. The address is in the next previous word, at offset -3. FIRST is a double-precision real, taking up two words. Therefore, offset -4 is the second word of the parameter, and offset -5 is the first word. G .5 CONFORMANT AR.RAY EXAMPLE Figure G-4 shows an example of an external procedure decl~ration with a conformant array parameter, and a picture of the stack after the call. The base address of the array is at offset -6; the length in words is at offset -5. The lower and upper bounds on the index are at offsets -3 and -2, respectively. The number of elements is at offset -4. G-5 PROCEDURE AND FUNCTION CALLING SEQUENCES PROCEDURE Confar(VAR a: ARRAyrJa .• ha:INTEGER] OF INTEGER); EXTERNAL; -6 (l 7) array base address fixed -5 (l 7) size part -4 (17) # elements -3(17) lower bound ( ] a) (per dimension) -2 (17) upper bound (ha) pa rt -1 (l 7) saved stack pointer 0 far ray (wo rd s) (ha-la+l) o (l7) return C'tddress Figure G-4: Conformant ArrAY Parameter G-6 variable INDEX -A/ABORT switch, 8-7 ABS function, 1-7, 6-13 Actual parameter, 5-14 AND operator, 1-6 3-5 ARCTAN function, ~-7, 6-13 Arithmetic expression, 3-1 Arithmetic functions, 6-13 Arithmetic operator, 1-8, 1-1 ARRAY, 1-0 ARRAY ~ata type, 2-8 Array examples, 2-15 Array type compatibility, 2-14 ASCII character set, 2-7, B-3 ASSIGN command, 9-3 Assigning a string constant, 2-12 a string variable, 2-11 values to an array, 2-12 values to records, 2-19 Assignment operator, 1-8 Assignment statement, 2-12, 5-2 Asterisk, 1-8 j' -BBACKUS-NAUR form, C-l Base type, 2-6, 2-22 BEGIN, 1-0, 1-9 Binary notation, 2-2 /BINARY switch, 8-7 Block, 1-2, 1-4 BNF syn tax, C-l BOOLEAN data type, 1-7, 2-2, 2-4 Boolean functions, 6-14 BOOLEAN results, 3-5 BREAK command, 9-4 -cCalling sequences function, G-l procedure, G-l CARD function, 1-7, 6-15 Caret, 1-8 CARRIAGE, 7-11 Carriage control, 7-11 Carriage control characters, 7-20 Case selector, 5-0 CASE statement, ]-0,2-17,5-4, 5-h Case-label list, 2-17, 5-0 CHAR data type, 1-7, 2-2, 2-4 Character set, 1-5 /CHECK switch, A-7, A-8 CHR function, 1-7, h-15 CLEAR command, 9-6 CLOCK function, 1-7, 6-15 CLOSE procedure, 1-7, G-5, 7-4 Collection of elements, ?-8 Colon, 1-8 Comma, 1-8 Command ASSIGN, 9-3 BREAK, 9-4 CLEAR, 9-6 DISPLAY, 9-7 EXECUTE, 8-17, 9-1 /EXIT, 8-5 EXIT, 9-9 /HELP, 8-5 HELP, 9-10 LOAD, 8-ln, 9-1 PROCEED, 9-10 RE~OVE, 9-11 /RUN, 8-5 RUN, 8-1 7 SAVE, 8-1 7 SET, 1-6, 9-11, 9-12, 9-13 SHOW, 9-14 START, 8-17, 9-1 /TAKE, A-5, 8-6 TRACE, 9-15 Comment, 1-8, 1-9 Compilation unit, 1-5 Compile-time errors, A-3 Compile-time warnings, A-18 Compiler listing format, 8-16 Compiling a program, 8-4 Component type, 2-24 Components, 2-8 Compound statement, 5-1, 5-2 Conditional statement, 5-4 Index·-l Conformant array, h-25 CONST, 1-6, 4-1, 4-4 Constant definition, 4-4 Constant identifier, 4-4 Constant name, 4-4 Control variable, 5-8 COS function, 1-7, 6-13 Creating a program, 8-3 /CREF switch, 8-7, 8-8 /CROSS-REFERENCE switch, 8-7, 8-8 -DData type, 2-1, 4-5, 4-f) ARRAY, 2-8 BOOLEAN, 1-7, 7.-2, 2-4 C HA R , 1 - 7, 2 - 2, 2- 4 DOUBLE, 1-7, 2-2 enume ra ted, 2-4 FILE, 2-8, 2-24 INTEGER, 1-7, 2-2 pointer, 2-1, 2-2n predefined, 2-2 REAL, 1-7, 2-2, 2-3 RECORD, 1-6, 2-8, 2-15 scalar, 2-1, 2-2, 2-4 SET, 2-8, 2-22 SINGLE, 1-7, 2-2 structured, 2-1, 2-8 subrange, 2-6 Data types, 1-2 DATE procedure, 1-7, 6-5, 6-12 Deallocating memory, 6-6 /DEBUG switch, 8-7, 8-8, 9-1 Debugger, 9-1 Debugging a program, 9-1 Decimal notation, 2-2 Declaration, 1-4 Declaration section, 4-1 Declaring a data type, 2-1 Definition, 1-4 Delimiter, 1-8 Direct access, 7-3, 7-10 DISPLAY command, 9-7 DISPOSE procedure, 1-7, f)-5, 6-6 DIV operator, 1-6 Division, 1-8 DO, 1-6, 5-8, 5-11, 5-12 Documenting your program, 1-9 Dollar sign, 1-7 DOUBLE data type, 1-7, 2-2 Double precision, 2-4 DOWNTO, 1-6, 5-8 Dynamic allocation procedure, 6-6 Dynamic variable, 2-26, 6-6 -EELSE clause, 1-6, 5-5 END, 1-6, 1-9 Enumerated data type, 2-5 EOF function, 1-7, 6-14 EOLN function, 1-7, 6-14 Equal, 1-8 /ERROR-LIMIT switch, 8-7, 8-8 Examples, 8-17 EXE file, 8-17 Executable statement, 1-4 EXECUTE command, 8-17, 9-1 Executing a program, 8-17 /EXIT command, 8-5 EXIT command, 9-9 EXP function, 1-7, h-13 EXPO function, 1-7, 6-16 Exponentintion, 1-8, 3-2 Expression, 3-1 a r i t hm e tic, 3-1 logical, 3-5 relational, 3-4 set, 3-5 Expression compatibility, 2-29 Extensions, D-1 EXTERNAL, f)-36 External file, 2-25, 4-2 External subprogram, f)-I, n-3h -F- FALSE, 1-7 Field identifier, 2-15 FILE, I-f) File TEXT, l-7 File characteristics, 7-2 FILE data type, 2-8, 2-24 File examples, 7-12 File history, 7-10 File organization, 7-3 File specification defaults, 8-3 File specifications, 8-2 File status, 7-10 File variable, 7-16 Final value, 5-8 FIND procedure, 1-7, 6-5, 7-4 FIXED, 7-11 Fixed length, 7-3 Fixed-length record, 7-3 /FLAG-NON-STANDARD switch, 8-7, 8-8 Floating-point format, 2-4 FOR statement, 1-6, 5-8 Formal and actual parameter compatibility, 2-29 Formal parameter, 6-20, 6-29, 6-32 FORTRAN, 6-29, 6-32, 6-36 FORWARD, 6-29, 6-32 FORWARD declaration, 6-35 FUNCTION, 1-6, 4-1 Function, 6-1 ABS, 1-7, 6-13 ARCTAN, 1-7, 6-13 CARD, 1-7, 6 -1 5 C HR, 1-7, 6 -15 CLOCK, 1-7, 6-15 COS, 1-7, 6 -13 Index-2 -L- Function (Cont.) EOF, 1-7, 6-14 EOLN, 1-7, 6-14 EXP, 1-7, 6 -13 EXPO, 1.-7, 6-16 LN, 1-7, 6 -13 ODD, 1-7, 6 -14 ORD, 1-7, 2-7, G-15 PRED, 1-7, 6-1 () ROUND, 1-7, 6-l~) SIN, 1-7, f)-14 SNGL, 1-7, f)-IS SQR, 1-7, 6-14 SQRT, 1-7, 6-14 SUCC, 1-7, 6-16 TRUNC, 1-7, 6-1~) UNDEFINED, 1-7, f)-IS Function calling sequences, G-l Function declaration, 6-32 Functions a r i t hm e tic, 6 -1 3 Boolean, 6-14 transfer, 6-15 LABEL, 1-6, 4-1, 4-1 Label, 5-13 Label declaration, 4-3 Less than, 1-8 Less than or equal, 1-8 Lexical elements, 1-5 LINELIMIT procedure, 1-7, 6-5, 7-7 LIST, 7-11 /LISTING switch, 8- 7 , 8-9, 8-11 LN function, 1-7, 6-13 LOAD command, 8-16, 9-1 Loading a program, 8-16 Local file, 2-25 Logical expression, 1-5 Logical operator, 3-1, 3-5 Loops, 5-8 Lower limit, 2-6 -M/MACHINE-CODE switch, 8-7, 8-9 Mark procedure, 6-5 MAXINT, 1-7, 2-3 Mechanism specifier, 6-21 '~inus sign, 1-8 MOD operator, 1-6 '~ODULE, 1-6, 6-37 I~odul es, t) -3 7 Multidimensional array, 2-9 Multiplication, 1-8 -GGET procedure, 1-7, 6-5, 7-6 GLOBAL, 6-29, 6-32 Global file, 2-2S GOTO statement, 1-6, 4-3, 5-13 Greater than, 1-8 Greater than or equal, 1-8 -8- -NHALT procedure, 1-7, 6-5 Heading, 1-2, 1-4 /HELP command, 8-5 HELP command, 9-10 Hexadecimal notation, 2-2 /NATIONAL switch, 8-7, 8--9 NEW procedure, 1-7, f)-5, 6-6 NIL, 1-6 NOCARRIAGE, 7-11 Not equal, 1-8 NOT operator, 1-6, 3-5 -I- -0- I/O errors, A-2 Identifier, 1-2, 1-7 IF statement, 1-6 IF-THEN statement, 5-4 IF-THEN-ELSE statement, 5-4, 5-5 IN, 1-6 %INCLUDE directive, 1-10 Included file, 1-10 Index, 2-8 Initial value, 5-8 Initializing a variable, 4-6 an array, 2-12 Initializing a variable, 4-7 INPUT, 1-7, 4-2 Input, 7-1 Input procedure, 6-5 INTEGER data type, 1-7, 2-2 Internal file, 2-25 Octal notation, 2-2 ODD function, 1-7, 6-14 OF, 1-6 OPEN procedure, 1-7, 6-5, 7-8 Operator, 3-1 AND, 1-6, 3-5 arithmetic, 1-8, 3-1 ass ignmen t, 1-8 DIV, 1-6 logical, 3-1 MOD, 1-6 NOT, 1-6, 3-5 OR, 1-6, 3-5 relational, 1-8, 2-11, 3-1, 3-4 REM, 1-6 set, 1-8, 3-1, 3-5 sub range , 1-8 OR operator. 1-6, 3-5 Index--3 INDEX ORD function, 1-7, 2-7, 6-15 o r d e red set, 2 - 5 Ordinal value, 2-7, 2-11 OTHERWISE clause, 1-6, 5-6 OUTPUT, 1-7, 4-2 Output, 7-1 Output procedure, 6-5 OVERLAID, 6-37 -p- PACK procedure, 1-7, ~-5, ~-10 PACKED, 1-6, 2-28 Packed array, 2-11,2-28 Packed file, 2-28 Packed record, 2-28 Packed set, 2-28 PAGE procedure, 1-7, 6-5, 7-14 Parameter, 6-21 act ua 1, 5 -1 4 formal, 6-20, 6-29, 6-32 Parentheses, 1-8 PASDDT, 9-1 PASDDT command, 9-3 Passing parameters, 6-22 Period, 1-8 Plus sign, 1-8 Pointer, 1-8 Pointer data type, 2-1, 2-26 Pointer variable, 6-6 Precedence of operators, 3-6 PRED function, 1-7, 6-16 Predecessor, 2-2 Predeclared fun c t ion, 6 -1 2 identifier, 1-7 procedure, 6-1 subprog ram, 6-1 Predefined data type, 2-2 PROCEDURE, 1-6, 4-1 Procedure, 6-1 CLOSE, 1-7, 6-5, 7-4 DATE, 1-7, 6-5, ~-12 DISPOSE, 1-7, 5-5, 6-6 FIND, 1-7, 6-5, 7-4 GET, 1-7, 6-5, 7-6 HALT, 1-7, 6-5 LINELIMIT, 1-7, ~-5, 7-7 MAHK, 6-5 NEW, 1-7, 6-5, 6-6 OPEN, 6-5, 7-8 PACK, 1-7, 6-5, 6-10 PAGE, 1-7, 6-5, 7-14 PUT, 1-7, 6-5, 7-15 READ, 1-7, 6-5, 7-16 READLN, 1-7, 6-5, 7-18 RELEASE, 6-5 RESET, 1-7, 6-5, 7-19 REWRITE, 1-7, 6-5, 7-20 TIME, 1-7, 6-5, 6-12 UNPACK, 1-7, ~-5, 6-11 WRITE, 1-7, 6-5, 7-21 WRITELN, 1-7, 6-5, 7-25 (Cont.) Procedure call, 5-14 Procedure calling sequences, G-l Procedure declaration, 6-28 Procedure identifier, 6-29 Procedure name, 5-14 PROCEED command, 9-10 PROGRAM, 1-5, 4-2 Program development, 8-1 Program heading, 4-1, 4-2 Program name, 4-2 Program structure, 1-2 PUT procedure, 1-7, 6-5, 7-15 -RRandom access, 7-3 READ procedure, 1-7, 6-5, 7-16 READ statement, 2-12 READLN procedure, 1-7, ~-5, 7-18 READLN statement, 2-12 REAL data type, 1-7, 2-2, 2-3 Record access, 7-3 Record access mode, 7-10 RECORD data type, 1-6, 2-8, 2-15 Record examples, 2-21 Record format, 7-3 Record length, 7-10 Recrrrd type, 7-11 Record type compatibility, 2-19 Record variable, 5-12 Records with variants, 2-17 Relational expression, 3-4 Relational operator, 1-8, 2-11, 3-1, 3-4 RELEASE procedure, 6-5 REM operator, 1-6 REMOVE command, 9-11 REPEAT statement, 1-6, 5-8, 5-10 Repetitive statement, 5-8 Reserved words, 1-~ RESET procedure, 1-7, 6-5, 7-19 Result type, 6-32 REWRITE procedure, 1-7, 6-5, 7-20 ROUND function, 1-7, 6-15 jRUN command, 8-5 RUN command, 8-17 Run-time errors, A-I -sSAVE command, 8-17 Scalar data type, 2-1, 2-2 Scientific notation, 2-4 Scope of identifiers, 3-7 Semicolon, 1-8 Semi reserved words, 1-6 Separate compilation, 6-37 Sepa ra to r, 1-8 Sequential access, 7-3, 7-10 SET command, 1-6, 9-11, 9-12, 9-13 SET data type, 2-8, 2-22 Set expression, 3-5 Index-4 INDEX Set operator, 1-8, 3-1, 3--5 Setting a breakpoint, 9-4 Shifting program control, 5-4 SHOW command, 9-14 Simple statement, 5-1 SIN function, 1-7, 6-14 SINGLE data type, 1-7, 2-2 Slash, 1-8 SNGL function, 1-7, 6-15 S P e cia 1 s ym bo 1 s, 1- 8 Specifying output files, 8-11 Specifying switches in source code, 8-9 SQR function, 1-7, 6-14 SQRT function, 1-7, 6-14 Square brackets, 1-8 START command, 8-17, 9-1 Statement assignment, 2-12, 5-2 CASE, 1-6, 2-17, 5-4, 5--6 compound, 5-1, 5-2 conditional, 5-4 FOR, 1-'5, 5-8 GOTO, l-6, 4-3, 5-13 IF, 1-6 IF-THEN, 5-4 IF-THEN-ELSE, 5-4, 5-5 READ, 2-12 READLN, 2-12 REPEAT, 1-6, 5-8, 5-10 repetitive, 5-8 simple, 5-1 WHILE, 1-6, 5-8, 5-11 WITH, 1-6, 5-12 String comparison, 2-1l String variable, 7-11 Structured data type, 2-1, 2-8 Subprogram, 1-4 Subprogram format, 6-20 Subprogram heading, 6-20 Subrange data type, 2-6 Subrange operator, 1-8 SUCC function, 1-7, 6-16 Successor, 2-2 Switch /ABORT, 8-7 /BINARY, 8-7 /CHECK, 8-7, 8-8 /CREF, 8-7, 8-8 /CROSS-REFERENCE, 8-7, 8-8 /DEBUG, 8-7, 8-8, 9-1 /ERROR-LIMIT, 8-7, 8-8 /FLAG-NON-STANDARD, 8-7, 8-8 /LISTING, 8-7, 8-9, 8-11 /MACHINE-CODE, 8-7, 8-9 /NATIONAL, 8-9 NATIONAL, 8-7 /WARNINGS, 8-9 /WARNINGs, 8-7 Symbolic values, 9-1 (Co n t. ) Syntax summary, C-l -T'rag field, 2-17 'rag name, /,-1 7 'rag type, 2-1 7 /TAKE command, 8-5, 8-6 Test condition, 5-5 TEXT file, 1-7, 2-12, 2-25 Text file, 2-25 'rHEN, 1-t; TIME procedure, 1-7, 6-5, 6-12 TO, 1-6, 5-8 TRACE command, 9-15 Transfer functions, ~-15 'rRUE, 1-7 TRUNC function, 1-7, 6-15 Truth value, 3-5 TYPE, 1-6, 4-1, 4-5 Type compatibility, 2-29 Type definition, 4-5 Type identifier, 4-5 TYPE section, 2-1 -uUNDEFINED function, 1-7, 6-15 Underscore, 1-7 UNPACK procedure, 1-7, 6-5, 6-11 UNTIL, 1-6, 5-10 Upper limit, 2-6 User identifier, 1-8 User-defined scalar data type, 2-5 -vVALUE, 1-6, 4-1, 4-7 Value declaration, 4-7 Value initialization, 4-7 Value parameter, 6-22 VAR, 1-6, 4-1, 4-6, 6-23 VAR section, 2-1 VARIABLE, 7-11 Variable declaration, 4-6 Variable length, 7-3 Variable name, 4-6 Variable parameter, 6-23 Variant clause, 2-15 -w/WARNINGS switch, 8-9 WARNINGS switch, 8-7 WHILE statement, 1-6, 5-8, 5-11 WITH statement, 1-6, 5-12 WRITE procedure, 1-7, 6-5, 7-21 WRITELN procedure, 1-7, 6-5, 7-25 Index-5 TOPS-20 PASCAL Language Manual AA-L31 5A-TM READEIR'S COMMENTS NOTE: This form is for document comments only. DIGITAL will use comments submitted on this form at the company's discretion. If you require a written reply and are eligible to receive one under Software Performance Report (SPR) service, submit your comments on an SPR form. Did you find this manual understandable, usable, and well-organized? Please make suggestions for improvement. Did you find errors in this manual? If so, specify the error and the page number. Please indicate the type of reader that you most nearly represent. D Assembly language programmer o Higher-level language programmer D Occasional programmer (experienced) D User with little programming experience D Student programmer D Other (please specify)~~~~_~~~~~~~~~~~~~~~~~~ Name ~~_~, ________________ Date _ _ _ _ _ _ _ _ _ _ __ Organization ___,________________ Telephone .,_ _ _ _ _ _ _ __ Street _____ ~, ______________________ City _ _ _ _ _ ,__________._ _ _ _ ~ ~ __________ State ____ Zip Code ______ or Country - Do Not Tear - Fold Here and Tape III II I DmDoma No Postage Necessary if Mailed in the United States BUSINESS REPLY MAIL FIRST CLASS PERMIT NO. 33 MAYNARD MASS. POSTAGE WILL BE PAID BY ADDRESSEE SOFTWARE PUBLICATIONS 200 FOREST STREET MR01-2/L12 MARLBOROUGH, MA 01752 Do Not Tear - Fold Here and Tape I I .= (1) ! I....J I~ It:: I 0 1° I~ 1.£ I~ I:; IW ! I
Home
Privacy and Data
Site structure and layout ©2025 Majenko Technologies