Pascal Reference
Pascal Reference
SunSoft, Inc.
A Sun Microsystems, Inc. Business
2550 Garcia Avenue
Mountain View, CA 94043 USA
415 960-1300 fax 415 969-9131
Please
Recycle
Contents
Preface. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . xix
1. Lexical Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Character Set . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 1
Special Symbols. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
Reserved Words . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
Identifiers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
Comments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
2. Data Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
Summary of Data Format Differences . . . . . . . . . . . . . . . . . . . 10
Default Data Alignments and Padding . . . . . . . . . . . . . . . 10
Data Formats with -calign. . . . . . . . . . . . . . . . . . . . . . . . 11
Data Formats with -xl . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Data Formats with -calign and -xl . . . . . . . . . . . . . . . . 12
real . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
real Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
iii
real Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
real Constants. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14
Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15
Integer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
Integer Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Integer Initialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Integer Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
boolean . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
boolean Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
boolean Initialization. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
boolean Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
Character . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Character Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Character Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 22
Character Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Enumerated Types . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
Enumerated Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Subrange . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Subrange Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Data Representation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
Contents v
Statements Specific to Pascal . . . . . . . . . . . . . . . . . . . . . . . . . . . 47
assert Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48
case Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51
exit Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 52
goto Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54
next Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56
otherwise Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58
return Statement . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 59
with Statement. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 60
4. Assignments and Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63
Data Type Assignments and Compatibility. . . . . . . . . . . . . . . 63
String Assignments. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64
Fixed- and Variable-Length Strings . . . . . . . . . . . . . . . . . . 64
Null Strings . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
String Constants . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 65
Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Arithmetic Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
The mod Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66
Bit Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
boolean Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68
The and then Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . 69
The or else Operator . . . . . . . . . . . . . . . . . . . . . . . . . . . . 70
Set Operators. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71
Relational Operators . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 72
Contents vii
argv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 105
arshft . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107
asl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109
asr . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111
card . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 112
clock. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113
close. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 116
concat . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117
date . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118
discard . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120
expo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123
filesize . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124
firstof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126
flush. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 130
getenv . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 132
getfile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 134
halt . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 136
in_range . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 138
index. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 139
land . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 142
lastof . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 144
length . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145
linelimit . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 147
lnot . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149
Contents ix
time . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 187
trace. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 189
trim . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 191
Type Transfer. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 193
wallclock . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 195
write and writeln. . . . . . . . . . . . . . . . . . . . . . . . . . . . . 198
xor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 200
7. Input and Output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
Input and Output Routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . 203
eof and eoln Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204
More About eoln . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208
External Files and Pascal File Variables . . . . . . . . . . . . . . . . . . 210
Permanent Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 210
Temporary Files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211
input, output, and errout Variables . . . . . . . . . . . . . . . . . 211
Properties of input, output, and errout Variables. . . 211
Associating input with a File Other Than stdin . . . . . 212
Associating output with a File Other Than stdout . . . 212
Associating errout with a File Other Than stderr . . . 212
Pascal I/O Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
Buffering of File Output. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 213
I/O Error Recovery. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 214
A. Overview of Pascal Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Lexical Elements . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219
Contents xi
D. Pascal Validation Summary Report . . . . . . . . . . . . . . . . . . . . . . 237
Test Conditions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237
Manufacturer’s Statement of Compliance . . . . . . . . . . . . . . . . 237
Implementation-Defined Features . . . . . . . . . . . . . . . . . . . 238
Reporting of Errors. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239
Implementation-Dependent Features . . . . . . . . . . . . . . . . 240
Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 240
Glossary . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 241
Index . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 255
xiii
xiv Pascal Language Reference
Tables
Table 1-1 Nonstandard Special Symbols. . . . . . . . . . . . . . . . . . . . . . . . . . . 2
xv
Table 2-12 Array Data Types. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34
Table B-1 Differences Between Programs Compiled with and without –xl 227
Tables xvii
xviii Pascal Language Reference
Preface
xix
In addition, Pascal 4.2 contains a compiler switch, -xl, to provide
compatibility with Apollo® DOMAIN® Pascal to ease the task of porting your
Apollo Pascal applications to workstations.
Note – All references to Pascal in this manual refer to the Sun Workshop
Compiler Pascal 4.2 unless otherwise indicated.
Audience
This manual provides reference material for the Pascal 4.2 compiler. To use this
manual, you should be familiar with ISO standard Pascal and with Solaris
commands and concepts.
Operating Environment
The Sun Workshop Compiler Pascal 4.2 runs on Solaris™ 2.x systems.
Installation
Instructions for installing Pascal and other software on your SPARCstation are
given in the Sun WorkShop Installation and Licensing Guide, which includes
information on installing the online documentation.
Preface xxi
Conventions Used in This Manual
This manual contains syntax diagrams of the Pascal language in extended
Backus-Naur Formalism (BNF) notation. It uses the following meta symbols:
The following table describes the type styles and symbols used in this manual:
Typeface or
Symbol Meaning Example
AaBbCc123 The names of commands, files, and Edit your .login file.
directories; on-screen computer Use ls -a to list all files.
output hostname% You have mail.
Shell Prompt
C shell prompt machine_name%
C shell superuser prompt machine_name#
Bourne shell and Korn shell prompt $
Bourne shell and Korn shell superuser prompt #
Related Documentation
This manual is designed to accompany the following documents:
• The Pascal User’s Guide, which describes how to use the Pascal 4.2 compiler
• The Pascal Quick Reference Card, which summarizes the compiler options
Both this manual and the Pascal User’s Guide are available in the AnswerBook®
system, an online documentation viewing tool that takes advantage of
dynamically linked headings and cross-references. The Sun WorkShop
Installation and Licensing Guide shows you how to install AnswerBook.
Manual Page
Pascal 4.2 provides an online manual page (also known as a man page), on
pc(1), that describes the Pascal compiler. This document is included in the
Pascal package and must be installed with the rest of the software.
After you install the documentation, you can read about pc by entering the
man command followed by the command name, as in:
hostname% man pc
README Files
The README default directory is: /opt/SUNWspro/READMEs
Preface xxiii
This directory contains the following files:
• A Pascal 4.2 README, called pascal, which describes the new features,
software incompatibilities, and software bugs of Pascal 4.2.
• A floating-point white paper, “What Every Scientist Should Know About
Floating-Point Arithmetic,” by David Goldberg, in PostScript™ format. The
file is called floating-point.ps, and can be printed on any PostScript-
compatible printer that has Palatino font. It can be viewed online by using
the imagetool command:
hostname% imagetool floating-point.ps
This chapter describes the symbols and words of a Pascal program. It contains
the following sections:
Character Set
Pascal uses the standard seven-bit ASCII character set, and the compiler
distinguishes between uppercase and lowercase characters. For example, the
following seven words are distinct from the predefined type integer:
Integer INTEGer
INteger INTEGEr
INTeger INTEGER
INTEger
If you change the case of characters used in a word, the compiler does not
recognize the word and gives an error.
1
1
The Pascal keywords and built-in procedure and function names are all in
lowercase.
To map all keywords and identifiers to lowercase when you compile your
program, use the following pc options:
See the Pascal 4.2 User’s Guide for a complete description of pc and its options.
Special Symbols
Pascal recognizes the following standard Pascal symbols and the nonstandard
special symbols listed in Table 1-1.
+ - * / = < > [ ] . , :=
: ; ( ) <> <= >= .. ^
Reserved Words
Pascal reserves the standard words in Table 1-2. You cannot redefine a
reserved word to represent another item.
Pascal also reserves the nonstandard words in Table 1-3. These words are not
treated as reserved words when you compile your program with any of the –s,
–s0, –s1, –V0 or –V1 options.
Lexical Elements 3
1
Identifiers
In Pascal, you can include a dollar sign ($) and underscore (_) in an identifier
name. The $ and _ can occur in any position of the identifier name. However,
you should avoid using these characters in the first position because they may
conflict with system names.
Pascal predeclares the standard identifiers in Table 1-4 and the nonstandard
identifiers in Table 1-5.
Once you redefine an identifier, you cannot use it as originally defined in the
program, as shown in the following example:
Lexical Elements 5
1
begin
for i := 1 to 10 do begin
if i > 5 then begin
next
end
end
end. { predefined_identifier }
Comments
In Pascal, you can specify a comment in either braces, quotation marks, a
parenthesis/asterisk pair, or a slash/asterisk pair:
{ This is a comment. }
(* This is a comment. *)
" This is a comment. "
/* This is a comment. */
The symbols used to delimit a comment must match. For example, a comment
that starts with { must end with }, and a comment that starts with (* must
end with *).
You cannot nest the same kind of comments. The following comments result in
a compile-time error:
{ This is not a valid { comment within a comment. } }
(* This is not a valid (* comment within a comment. *) *)
" This is not a valid " comment within a comment. " "
/* This is not a valid /* comment within a comment. */ */
Lexical Elements 7
1
This chapter describes the Pascal data types. Some data types represent
different values when you compile your program with or without the –xl
option, and with or without the –calign option. The intent of the –xl option
is to guarantee binary data compatibility between the operating system and
Apollo MC680x0-based workstations. The intent of the -calign option is to
improve compatibility with C language data structures.
9
2
All simple data types take their natural alignments. For example, real
numbers, being four-byte values, have four-byte alignment. Naturally, no
padding is needed for simple types.
Records
The alignment of a record is always four bytes. Elements take their natural
alignment, but the total size of a record is always a multiple of four bytes.
Packed Records
Elements of types enumerated, subrange, integer16, and sets with a cardinal
number less than 32 are bit-aligned in packed records.
Variant Records
The alignment of each variant in a record is the maximum alignment of all
variants.
Arrays
The alignment of a array is equal to the alignment of the elements, and the size
of most arrays is simply the size of each element times the number of elements.
The one exception to this rule is that the arrays of aggregates always have a
size that is a multiple of four bytes.
Sets
Sets have an alignment of four bytes when they are longer than 16 bits;
otherwise, their alignment is two bytes. The size of a set is always a multiple
of two bytes.
Enumerated Types
The size and alignment of enumerated types can be one byte or two,
depending on the number of elements defined for the type.
Subranges
The size and alignment of subrange types varies from one to four bytes,
depending on the number of bits requires for its minimum and maximum
values. See Table 2-7 on page 26 for examples.
Records
The alignment of a record is equal to the alignment of the largest element.
Packed Records
Packed records are the same as the default, except integer elements are not bit-
aligned.
Arrays
The size of all arrays is the size of each element times the number of elements.
Sets
Sets have an alignment of two bytes. The size is the same as the default.
Data Types 11
2
Packed Records
Values of type real have four-byte sizes and alignment. Values of type
integer have a size of two bytes and are bit-aligned.
Enumerated Types
The size and alignment of enumerated types is always two bytes.
Subranges
The size and alignment of subrange types varies from two to four bytes,
depending on the number of bits requires for its minimum and maximum
values. See Table 2-7 for examples.
Arrays
Arrays are the same as with -calign alone, except the size of an array of
booleans is always a multiple of two.
Varying Arrays
Varying arrays have an alignment of four bytes. The size is a multiple of four.
real
Pascal supports the standard predeclared real data type. As extensions to the
standard, Pascal also supports:
• single, shortreal, double, and longreal data types
• real initialization in the variable declaration
• real constants without a digit after the decimal point
real Variables
The minimum and maximum values of the real data types are shown in
Table 2-1.
var x: real;
y: shortreal;
z: longreal;
weight: single;
volume: double;
real Initialization
To initialize a real variable when you declare it in the var declaration of your
program, create an assignment statement as follows:
Data Types 13
2
You can also initialize real variables in the var declaration of a procedure or
function; however, when you do so, you must also declare the variable as
static:
The example in the following section defines six valid real constants, two of
which do not have a digit after the decimal point.
real Constants
Here is an example that of a real constant:
const
n = 42.57;
n2 = 4E12;
n3 = 567.;
n4 = 83.;
n5 = cos(567.)/2;
n6 = succ(sqrt(5+4));
Data Representation
Pascal represents real, single, shortreal, double, and longreal data
types according to the IEEE standard, A Standard for Binary Floating-Point
Arithmetic. Figure 2-1 shows the representation of a 32-bit floating point
number; Figure 2-2 shows the representation of a 64-bit floating point number.
Figure 2-1 32-Bit Floating-Point Number
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
63 62 61 60 59 58 57 56 55 54 53 52 51 50 49 48 47 46 45 44 43 42 41 40 39 38 37 36 35 34 33 32
Exponent + 1023 Mantissa
S
Mantissa (continued)
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Exponent Description
zero (signed) Represented by an exponent of zero and a fraction of zero.
sign 1-bias
Subnormal number Represented by (-1) *2 *0.f, where f is the bits in the
significand.
Not a Number (NaN) Represented by the largest value that the exponent an assume
(all ones), and a nonzero fraction.
Normalized real numbers have an implicit leading bit that provides one more
bit of precision than usual.
Data Types 15
2
Table 2-3 shows the hexadecimal representation of several numbers.
Integer
Pascal supports the standard predeclared integer data type. As extensions to
the standard, Pascal also supports the integer16 and integer32 data types,
integer initialization in the variable declaration, and integer constants in a base
other than base 10.
Integer Variables
Table 2-4 lists the minimum and maximum values of the integer data types.
var
i: integer;
score: integer16;
number: integer32;
Data Types 17
2
Integer Initialization
To initialize integer variables when you declare them in the var declaration
part of your program, put an assignment statement in the declaration, as
follows:
You can also initialize integer variables in the var declaration of a procedure
or function; however, when you do so, you must also declare the variable as
static:
Integer Constants
You define integer constants in Pascal the same as you do as in standard
Pascal.
Here is an example:
const
x = 10;
y = 15;
n1 = sqr(x);
n2 = trunc((x+y)/2);
n3 = arshft(8, 1);
In Another Base
To specify an integer constant in another base, use the following format:
base#number
You can optionally put a positive sign (+) or negative sign (-) before base. The
sign applies to the entire number, not the base.
Data Representation
Pascal represents integer, integer16, and integer32 data types in twos
complement format. Figure 2-3 shows the representation of a 16-bit integer.
Similarly, Figure 2-4 shows the representation of a 32-bit integer.
Data Types 19
2
Figure 2-3 16-Bit Integer
Byte 0 Byte 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
boolean
Pascal supports the standard predeclared data type boolean. As an extension
to the standard, Pascal permits you to initialize boolean variables in the
variable declaration.
boolean Variables
In Pascal, you declare boolean variables the same as in standard Pascal. Both
of the following are valid boolean variables:
boolean Initialization
To initialize a boolean variable when you declare it in the var declaration of
your program, use an assignment statement, as follows:
This code initializes the variable function weather (x: integer): boolean;
rainy to false, which has
been declared as static var
boolean. rainy: static boolean := false;
boolean Constants
You declare boolean constants in Pascal the same as in standard Pascal.
Three valid boolean constants follow:
Data Representation
Pascal allocates one byte for each boolean variable. Figure 2-5 shows how
Pascal internally represents a true boolean variable; Figure 2-6 shows how
Pascal represents a false boolean variable.
0 0 0 0 0 0 0 1
7 6 5 4 3 2 1 0
Data Types 21
2
0 0 0 0 0 0 0 0
7 6 5 4 3 2 1 0
Character
Pascal supports the standard predeclared data type char. As extensions to the
standard, Pascal supports character initialization in the variable declaration
and four nonstandard character constants.
Character Variables
You declare character variables in Pascal the same as you do in standard
Pascal. Each of the following is a valid character variable:
var
current_character: char;
largest: char;
smallest: char;
Character Initialization
To initialize a character variable when you declare it in the var declaration of
your program, create an assignment statement, as follows:
Character Constants
Pascal extends the standard definition of character constants by predeclaring
the four character constants in Table 2-6.
Constant Description
minchar Equal to char(0)
maxchar Equal to char(255)
bell Equal to char(7) (which makes your terminal beep)
tab Equal to char(9) (which makes a tab character)
Data Representation
Pascal allocates one byte for each character variable.
Enumerated Types
Pascal supports enumerated data types with extensions that allow you to input
enumerated types with the read and readln procedures and output them
with the write and writeln procedures. See the listings on read and write
in Chapter 7, “Input and Output,” for details.
Data Types 23
2
Enumerated Variables
You declare enumerated data types in Pascal the same as in standard Pascal.
type
continents =(North_America, South_America,
Asia, Europe, Africa, Australia,
Antartica);
gem_cuts = (marquis, emerald, round, pear_shaped);
var
x: gem_cuts;
index: continents;
Data Representation
When you compile your program without the –xl option, Pascal represents
enumerated types as either 8 or 16 bits, depending on the number of elements
defined for that type. With -xl, Pascal represents variables of enumerated
type as 16 bits. Pascal stores enumerated types as integers corresponding to
their ordinal value.
Byte 0 Byte 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
Red Green
0 0 0 0 0 0 1 0 0 0 0 0 0 0 1 1
7 6 5 4 3 2 1 0 7 6 5 4 3 2 1 0
Blue Orange
Subrange
Pascal supports a subrange of integer, boolean, character, and enumerated
data types.
The Pascal subrange type is extended to allow constant expressions in both the
lower and upper bound of the subrange. The lower bound expression is
restricted by requiring that the expression not begin with a left parenthesis.
Subrange Variables
See “Integer Variables” on page 17 for an example of a subrange declaration.
Data Representation
The Pascal subrange takes up the number of bits required for its minimum and
maximum values. Table 2-7 shows the space allocation of six subranges.
Data Types 25
2
Byte 0 Byte 1
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Record
Pascal supports the standard record and packed record data types. As an
extension, Pascal permits you to initialize a record variable when you declare it
in the variable declaration.
Record Variables
You declare records in Pascal the same as in standard Pascal, as shown in the
following example:
type
MonthType = (Jan, Feb, Mar, Apr, May, Jun, Jul,
Aug, Sep, Oct, Nov, Dec);
DateType = record
Month : MonthType;
Day : 1..31;
Year : 1900..2000;
end;
Appointment = record
Date : DateType;
Hour : 0..2400;
end;
Record Initialization
To initialize a field in a record when you declare it in the var declaration of
your program, use either of the following two formats:
• Specify the record field name followed by an assignment operator and
initial value.
[a := FALSE ,
b := TRUE ]
• List the initial value without the field name. In this case, Pascal assigns the
initial value to the next field name in the record definition.
[ FALSE ,
TRUE ]
Data Types 27
2
You can also initialize record variables in the var declaration of a procedure or
function; however, when you do so, you must also declare the variable as
static.
{ Initialization by position. }
rec2: record_type :=
['X',
['x', 'y', 'z'],
'ARRAY2',
red,
true];
{ Initialization by name and position. }
rec3: record_type :=
[colors := red,
true,
1.16,
st := ['m', 'n', 'o'],
'ARRAY3'];
begin
writeln('char ', rec1.c);
writeln('char array ', rec1.z);
writeln('integer ', rec1.i16);
writeln;
writeln('char ', rec2.c);
writeln('char array ', rec2.z);
writeln('boolean ', rec2.b);
writeln;
writeln('char array ', rec3.z);
writeln('boolean ', rec3.b);
writeln('single ', rec3.s)
end. { record_example }
Data Types 29
2
char X
char array ARRAY2
boolean true
Fixed Records
Pascal allocates fields in a fixed record so that they assume the natural
alignment of the field type. The alignment of a record is equal to the alignment
of the largest element. The size of the record is a multiple of the alignment.
Variant Records
The space Pascal allocates for a variant record is the same with or without the
–xl option.
Data Types 31
2
The following example declares a packed record. Table 2-11 shows the
alignment and sizes of the fields of the record. Figure 2-11 shows the
representation of this record.
type
small = 0..128;
medium = 0..255;
large = 0..65535;
colors = (green, blue, orange, white, black, magenta, gray);
sets = (autumn, summer, winter, fall);
vrec1 = packed record
a: integer16;
b: boolean;
e: colors;
sm: small;
med: medium;
lg: large;
se: sets;
x: integer32;
end;
b e sm med
med
lg
lg se
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Data Types 33
2
Array
Pascal supports the standard array data type. As extensions to the standard,
Pascal supplies the predeclared character array types alfa, string, and
varying and permits you to initialize an array variable when you declare it in
the variable declaration.
Array Variables
In addition to the standard array data types, this compiler supports the three
data types in Table 2-12, which include a variable-length string.
Type Description
alfa An array of char 10 characters long.
string An array of char 80 characters long.
varying A string of variable length. You declare a varying string as follows:
varying[upper_bound] of char; upper_bound is an integer
between 0 and 65,535
var
name1: array [1..25] of char; { String of size 25. }
name2: array [76..100] of char; { String of size 25. }
name3: alfa; { String of size 10. }
name4: string; { String of size 80. }
name5: varying [25] of char; { Varying string. }
name6: varying [25] of char; { Varying string. }
begin
name1 := 'van Gogh';
name2 := 'Monet';
name3 := 'Rembrandt';
name4 := 'Breughel';
name5 := 'Matisse';
name6 := 'Cezanne';
writeln(name1, ' and ', name2, '.');
writeln(name3, ' and ', name4, '.');
writeln(name5, ' and ', name6, '.')
end. { varying_example }
Data Types 35
2
Array Initialization
To initialize an array variable when you declare it in the var declaration of
your main program, use an assignment statement after the declaration. Pascal
offers you the following four different formats:
• Supply the lower and upper bounds in the initialization.
• Put an asterisk in place of the upper bound, and let the compiler determine
the upper bound once it counts the initial values. You can use this format
only when you also supply the initial values.
When you initialize an array in the var declaration, the compiler sets those
elements for which it doesn’t find data to zero.
You can also initialize array variables in the var declaration of a procedure or
function; however, you must also declare the variable as static.
Packed Arrays
Although you can define an array as packed, it has no effect on how the
Pascal compiler allocates the array data space.
Data Representation
The elements of an array require the same space as that required by the base
type of the array. However, there are two exceptions to this. With the
-calign option, the size of all arrays is the size of each element times the
number of elements. When you use the -calign and -xl options together,
arrays are the same as with -calign alone, except the size of an array of
booleans is always a multiple of two.
Data Types 37
2
Set
Pascal supports sets of elements of integer, boolean, character, and
enumerated data types. As extensions to the standard, Pascal predefines a set
of intset; you can then initialize a set variable when you declare it in the var
declaration of your program.
Set Variables
In Pascal, you declare set variables the same as you do in standard Pascal. The
following is a valid set variable:
type
character_set = set of char;
var
letters: character_set;
Set Initialization
To initialize a set variable when you declare it in the var declaration of your
program, create an assignment statement, as follows:
Packed Sets
Although you can define a set as packed, it has no effect on how the compiler
allocates the set data space.
Data Representation
Pascal implements sets as bit vectors, with one bit representing each element of
a set. The maximum ordinal value of a set element is 32,768.
The size of a set is determined by the size of the ordinal value of maximal
element of the set plus one. Sets are allocated in multiples of 16 bits; therefore,
the smallest set has size 16 bits. The ordinal value of the minimal element
must be equal to or greater than 0. Sets have an alignment of four bytes when
they are longer than 16 bits; otherwise their alignment is two bytes. For
example, 'set of 1..20' has a four-byte alignment and 'set of 1..15' has a two-byte
alignment.
With the -calign option, sets have an alignment of two bytes. The size is the
same as the default.
Data Types 39
2
Table 2-13 shows the data representation of four sets.
Set Description
set of 0..15 This set requires 16 bits because 15 is the maximal element, and
15 + 1 = 16.
set of 0..16 This set requires 32 bits because 16 is the maximal element. 16 + 1 = 17,
and the next multiple of 16 above 17 is 32.
set of 14..15 This set requires 16 bits because 15 is the element, and 15 + 1 = 16.
set of char This set requires 256 bits because the range of char is
chr(0)..chr(255). The ordinal value of the maximal element is 255,
and 255+1 = 256, which is divisible by 16.
You can visualize the bit vector representation of a set as an array of bits
starting from the highest element to the lowest element. For example, the
representation of the following set is shown in Figure 2-12.
var
smallset: set of 2..15 := [7,4,3,2];
0 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0
15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
var
largeset: set of 2..255 := [7,4,3,2];
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 1 0 0 1 1 1 0 0
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Loc +1 Loc +1
Loc +0
File
Pascal treats files declared as file of char the same as files declared as
text, except when you use the –s –s0, –s1, –V0, or –V1 options. In this case,
the compiler treats the two data types differently, as required by standard
Pascal.
Pointer
Pascal supports the standard Pascal pointer and the nonstandard universal
pointer and procedure and function pointer.
Standard Pointer
The standard pointer is the same in Pascal and standard Pascal.
Data Types 41
2
Universal Pointer
The universal pointer data type, univ_ptr, is compatible with any pointer
type. Use univ_ptr to compare a pointer of one type to another, to assign a
pointer of one type to another, or to weaken type checking when passing
parameters of pointer types.
You cannot dereference a univ_ptr variable: you cannot find the contents of
the address to which univ_ptr points.
var
i: integer32;
r: single;
ip: ^ integer32;
rp: ^ single := addr(r);
up: univ_ptr;
begin
r := 10.0;
{ The next two statements are equivalent to rp := ip.
However, rp := ip is not legal since they are
different types. }
up := rp;
ip := up;
writeln(ip^ hex);
{ This will do the same thing but uses transfer functions. }
writeln(integer32(r) hex)
end. { univ_ptr_example }
Data Types 43
2
procedure printred;
begin
writeln('RED')
end; { printred }
procedure printwhite;
begin
writeln('WHITE')
end; { printwhite }
procedure printblue;
begin
writeln('BLUE')
end; { printblue }
var
{ Array of procedure pointers. }
colorprinter: array [colors] of procptr :=
[addr(printred),
addr(printwhite),
addr(printblue)];
c: colors;
desc_proc: procptr;
begin
write('Enter red, white, or blue: ');
readln(c);
desc_proc := colorprinter[c];
desc_proc^
end. { pointer_example }
Pointer Initialization
To initialize a pointer variable when you declare it in the var declaration of
your program, use an assignment statement, as follows:
You can also initialize pointer variables in the var declaration of a procedure
or function; however, when you do so, you must also declare the variable as
static.
Data Representation
Pascal represents a pointer as shown in Figure 2-14.
Address
31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0
Data Types 45
2
Standard Statements
Pascal supports all standard statements. Pascal also supports extensions to:
assert next
case otherwise
exit return
goto with
47
3
Statement Description
assert Causes a boolean expression to be evaluated each time the
statement is executed.
case Accepts ranges of constants and an otherwise statement.
exit Transfers program control to the first statement after the end of a
for, while, or repeat loop.
goto Accepts an identifier as the target of goto.
next Causes the program to skip to the next iteration of the enclosing for,
while, or repeat loop.
otherwise An extension to the case statement. If the expression in a case
statement does not match any of the case values, the compiler
executes the statements under the otherwise statement.
return Prematurely ends a procedure or a function.
with An alternative format to the standard with statement.
assert Statement
The assert statement causes a boolean expression to be evaluated each time
the statement is executed.
If your program contains an assert statement, you must compile it with the
–C option, which enables runtime tests. Otherwise, the compiler treats
assert as a comment.
Statements 49
3
begin
num := 6;
assert((num > 0) and (num <= MAX_STUDENTS));
for i := 1 to num do begin
write('Enter grade for student ', i: 3, ': ');
readln(grades[i])
end
end. { assert_example }
hostname% pc -C -g assert.p
hostname% a.out
Assertion #1 failed
Trace/BPT trap (core dumped)
case Statement
Pascal supports the standard case statement with extensions for an
otherwise clause and ranges of constants.
If expression does not match any of the case values, the compiler executes the
otherwise statement list. The reserved word otherwise is not a case label,
so it is not followed by a colon (:). Also, the begin/end pair is optional in an
otherwise statement.
You can use a range of constants instead of a single case value. A case range
must be in ascending order.
The case statement operates differently when you compile your program with
and without the –xl option. Without –xl, if the value of the expression is not
equal to one of the case labels and you omit the otherwise statement, the
program generates an error and halts.
If this situation occurs and you compile your program with –xl, the program
falls through and does not generate an error; program execution continues
with the statement immediately following the case statement.
Statements 51
3
exit Statement
The exit statement, which you can use in a for, while, or repeat loop,
transfers program control to the first statement after the end of the current
loop.
If used in a nested loop, exit only breaks out of the innermost loop.
You receive a compile-time error if you use this statement anywhere but in a
for, while, or repeat loop.
const
MAX = 10;
type
integer_type = array [1..MAX] of integer16;
var
i: integer16;
i_array: integer_type := [1, 99, 13, 45, 69, 18, 32, -6];
number: integer16;
flag: boolean := false;
begin
write('Enter a number: ');
readln(number);
for i := 1 to MAX do begin
if number = i_array[i] then begin
flag := true;
exit
end
end;
if flag then
writeln('Number WAS found: ', number)
else
writeln('Number WAS NOT found: ', number)
end. { exit_example }
Statements 53
3
goto Statement
Pascal supports the standard format of the goto statement with two
extensions.
In Pascal, you can use an identifier as the target of a goto. Standard Pascal
allows only integers as targets of gotos.
If you use a goto to jump out of the current block, Pascal closes all open files
in the intervening blocks between the goto statement and the target of the
goto.
label
skip_subtotal;
const
MAX_STUDENTS = 100;
var
i: integer;
grades: array [1..MAX_STUDENTS] of char;
num: 1..MAX_STUDENTS;
sum: real;
points: real;
begin
{ Read in number of students and their grades. }
write('Enter number of students: ');
readln(num);
assert((num > 0) and (num < MAX_STUDENTS));
for i := 1 to num do begin
write('Enter grade for student ', i: 3, ': ');
readln(grades[i])
end;
writeln;
{ Now calculate the average GPA for all students. }
sum := 0;
for i := 1 to num do begin
if grades[i] = 'I' then begin
goto skip_subtotal
end else begin
case grades[i] of
'A': points := 4.0;
'B': points := 3.0;
'C': points := 2.0;
'D': points := 1.0;
'F': points := 0.0;
Statements 55
3
otherwise
writeln('Unknown grade: ', grades[i]);
points := 0.0
end
end;
sum := sum + points;
skip_subtotal:
end;
writeln('GPA for all students is ', sum / num: 6: 2, '.')
end. { goto_example }
next Statement
The next statement, which you can only use in a for, while, or repeat loop,
causes the program to skip to the next iteration of the current loop, thus
skipping the rest of the statements in the loop.
The next statement has the same effect as a goto to the end of the loop. If
you use next in a for loop, Pascal increments the index variable as normal.
When you use next in a nested loop, it goes to the end of the innermost loop
containing the next statement.
You receive a compile-time error if you use this statement anywhere but in a
for, while, or repeat loop.
const
MAX_STUDENTS = 100;
var
i: integer;
grades: array [1..MAX_STUDENTS] of char;
num: 1..MAX_STUDENTS;
sum: real;
points: real;
begin
{ Read in number of students and their grades. }
write('Enter number of students: ');
readln(num);
assert((num > 0) and (num <= MAX_STUDENTS));
for i := 1 to num do begin
write('Enter grade for student ', i: 3, ': ');
readln(grades[i])
end;
writeln;
Statements 57
3
otherwise Statement
The otherwise statement is a Pascal extension to the standard Pascal case
statement. If specified, otherwise must be at the end of the case statement.
See the listing in “case Statement” on page 51 for additional information.
return Statement
The return statement prematurely ends a procedure or a function.
Program control transfers to the calling routine. This has the same effect as a
goto to the end of the routine. If used in the main program, return causes
the program to terminate.
procedure test;
label
error_negative_value, error_bad_values, error_value_too_big;
begin
if i < 0 then
goto error_negative_value
else if (i = 2) or (i = 3) then
goto error_bad_values
else if i > 100 then
goto error_value_too_big;
return;
error_negative_value:
writeln('Value of i must be greater than 0.');
return;
error_bad_values:
writeln('Illegal value of i: 2 or 3.');
return;
error_value_too_big:
writeln('Value of i too large.');
return
end; { test }
Statements 59
3
with Statement
Pascal supports the standard with statement plus an alternative format.
const
MAX = 12;
type
name_type = varying [MAX] of char;
Patient =
record
LastName: name_type;
FirstName: name_type;
Sex: (Male, Female)
end;
var
new_patient: Patient;
old_patient: Patient;
begin
with new_patient: new, old_patient: old do begin
new.LastName := 'Smith';
new.FirstName := 'Abby';
new.Sex := Female;
old.LastName := 'Brown';
old.FirstName := 'Henry';
old.Sex := Male
end;
write('The new patient is ');
write(new_patient.FirstName: 10);
writeln(new_patient.LastName: 10, '.');
write('The old patient is ');
write(old_patient.FirstName: 10);
writeln(old_patient.LastName: 10, '.')
end. { with_example }
Statements 61
3
63
4
String Assignments
Pascal has special rules for assigning fixed- and variable-length strings, null
strings, and string constants.
The valid fixed- and variable-length string assignments are given in Table 4-2.
Null Strings
Pascal treats null strings as constant strings of length zero. Table 4-3 shows the
null string assignments.
Assignment Description
varying := ''; The compiler assigns the null string to the variable-
length string. The length of the variable-length string
equals zero.
array of char := ''; The compiler assigns a string of blanks to the character
array. The length of the resulting string is the number
of elements in the source character array.
char := ''; It is illegal to assign a null string to a char variable.
Use chr(0) instead.
String concatenation In a string concatenation expression such as:
S := 'hello' + '' + S;
'' is treated as the additive identity (as nothing).
String Constants
When assigning a constant string to a packed array of char, standard
Pascal requires that the strings be the same size.
Pascal allows the constant string and packed array of char to be unequal
in size, truncating the constant string if it is longer or padding it with blanks if
it is shorter.
Operators
Pascal supplies six classes of operators:
• Arithmetic operators
• Bit operators
• boolean operators
• Set operators
• Relational operators
• String operators
Arithmetic Operators
The arithmetic operators are summarized in Table 4-4.
equals:
-1 * remainder of |i| divided by |j|
var
i: integer;
j: integer;
begin
for i := -3 to -1 do
for j := 1 to 3 do
if j <> 0 then
writeln(i: 4, j: 4, i mod j: 4)
end. { mod_example }
Bit Operators
Table 4-5 shows the bit operators. The ~ operator produces the same results as
the built-in Pascal function, lnot. Similarly, & is equivalent to the function,
land; | and ! are equivalent to lor. See Chapter 7, “Input and Output,” for
descriptions of these functions and the truth tables that both the functions and
the operators use.
boolean Operators
The boolean operators, which include the nonstandard and then and or else
operators, are summarized in Table 4-6.
However, when you use the following syntax, the compiler always evaluates
odd(x) first:
odd(x) and then odd(y)
Note – You cannot insert comments between the and and the then operators.
var
x, y: integer16;
begin
write('Please enter two integers: ');
readln(x, y);
if odd(x) and then odd(y) then
writeln('Both numbers are odd.')
else
writeln('Both numbers are not odd.');
end. { and_then }
Note – You cannot insert comments between the or and the else operators.
var
x, y: integer16;
begin
write('Please enter two integers: ');
readln(x, y);
if (x < 10) or else (y < 10) then
writeln('At least one number is less than 10.')
else
writeln('Both numbers are greater than or equal to 10.');
end. { or_else }
Set Operators
The set operators in Table 4-7 accept different set types as long as the base
types are compatible. The relational operators can also be used to compare
set-type values.
Relational Operators
The relational operators are given in Table 4-8. In Pascal, you can apply all
relational operators to sets and the equality (=) and inequality (<>) operators
on records and arrays.
begin
set1 := [orange, yellow];
set2 := [red, orange, yellow];
writeln(set1 > set2);
writeln(set1 < set2)
end. { set_example }
In making comparisons, between arrays and records, make sure the operands
are of the same type.
type
Shape = (Square, Trapezoid, Rectangle);
variant_record =
record
case Shape_type: Shape of
Square: ( side1: real );
Trapezoid: ( top1: real;
bottom: real;
height: real );
Rectangle: ( length: real;
width: real )
end;
normal_record =
record
name: array [1..MAX] of char;
avg: integer;
grade: char
end;
var
class1: normal_record := ['Susan', 100];
class2: normal_record := ['John', 99];
shapes1: variant_record;
shapes2: variant_record;
begin
{ Should PASS. }
if class1 <> class2 then
writeln('PASSED')
else
writeln('FAIL');
shapes1.Shape_type := Rectangle;
shapes2.Shape_type := Square;
{ Should PASS }
if shapes1 = shapes2 then
writeln('FAIL')
else
writeln('PASSED');
shapes1.Shape_type := Trapezoid;
shapes2.Shape_type := Trapezoid;
{ Should PASS. }
if shapes1 = shapes2 then
writeln('PASSED')
else
writeln('FAIL')
end. { record_example }
String Operators
With the string concatenation operator, the plus sign (+), you can concatenate
any combination of varying, array of char, constant strings, and single
characters.
var
col: varying [10] of char := 'yellow';
fish: array [1..4] of char := 'tail';
n1: char := 'o';
n2: char := 'r';
begin
write(fish + n1 + n2 + 'bird ', col + 'bird ');
writeln(col + fish)
end. { string_example }
Precedence of Operators
Table 4-9 lists the order of precedence of Pascal operators, from the highest to
the lowest.
Operators Precedence
~, not, Highest
*, /, div, mod, and, &, .
|, !, +, -, or, .
=, <>, <, <=, >, >=, in, .
or else, and then Lowest
Declarations page 77
Procedure and Function Headings page 84
Declarations
This section describes the label, constant, type, variable, and define
declarations. Procedure and function declarations are described in Chapter 6,
“Built-In Procedures and Functions.”
Label Declaration
The label declaration defines labels, which are used as the target of goto
statements.
Comments
In Pascal, you can use both identifiers and integers as labels. Using identifiers
as labels makes your code easier to read.
77
5
Example
var
i: integer;
procedure test;
label
error_negative_value, error_bad_values, error_value_too_big;
begin
if i < 0 then
goto error_negative_value
else if (i = 2) or (i = 3) then
goto error_bad_values
else if i > 100 then
goto error_value_too_big;
return;
error_negative_value:
writeln('Value of i must be greater than 0.');
return;
error_bad_values:
writeln('Illegal value of i: 2 or 3.');
return;
error_value_too_big:
writeln('Value of i too large.');
return
end; { test }
Constant Declaration
The constant declaration defines constants, values that do not change during
program execution.
Example
Type Declaration
The type declaration describes and names types used in variable, parameter,
and function declarations.
Program Declarations 79
5
Unlike standard Pascal, in Pascal, you can define universal pointer types and
procedure and function pointer types in the type declaration.
Example
Variable Declaration
The variable declaration declares variables.
In the variable declaration, you can specify the variable scope, attributes, and
initial values. In most cases, you do not have a variable declaration that has
both a variable scope and a variable attribute, because these are different ways
for doing similar things.
Scope
The scope of a variable is either private or public.
• A private variable is visible in the current compilation unit only.
• A public variable is visible across multiple programs and modules.
private var
score: integer16 := 99;
Attributes
The variable attributes determine how to allocate the variable and its scope.
They include static, extern, and define.
static
A static variable is a variable that is private in scope and which is
allocated statically. A global variable declared as static is equivalent to a
variable that has been declared private. Pascal generates a compile-time
error if you attempt to declare a global variable as both static and public.
When you declare a local variable as static, the variable retains its value
after the program exits the procedure in which it is declared. You can only
initialize a local variable, that is, a variable declared in a procedure, in the var
declaration if you also declare it as static.
Program Declarations 81
5
var
i: integer;
procedure count;
var
number_of_times_called: static integer := 0;
begin
number_of_times_called := number_of_times_called + 1;
writeln('Call number: ', number_of_times_called)
end; { count }
extern
The extern attribute is used to declare a variable that is not allocated in the
current module or program unit, but is a reference to a variable allocated in
another unit. You cannot initialize extern variables. See the Pascal 4.2 User’s
Guide, which describes separately compiled programs and modules; it also
contains examples of the extern attribute.
Initialization
You can initialize real, integer, boolean, character, set, record, array, and
pointer variables in the var declaration. You cannot initialize a local variable
(a variable in the var declaration of a procedure or function) unless you
declare it as static.
Define Declaration
The define declaration controls the allocation of variables.
Program Declarations 83
5
Comments
The value of identifier must correspond to either a variable or procedure or
function identifier. If identifier corresponds to a variable, it must have a
matching variable declaration with the extern attribute. The define
declaration nullifies the meaning of extern: it allocates the variable in the
current program or module unit.
You can initialize variables, but not procedures and functions, in the define
declaration. Identifiers in the define declaration are always public.
Example
See the chapter on separate compilation in the Pascal 4.2 User’s Guide for
examples of the define declaration.
Visibility
You can declare a procedure or function at the outer block level as either
public or private.
Procedures and functions declared within a module unit are always public.
For additional information on modules, see the Pascal 4.2 User’s Guide.
Parameter List
Pascal supplies the parameter types in, out, in out, var, value, and univ.
Program Declarations 85
5
in Indicates that the parameter can only pass a value into the routine. The
parameter is, in effect, a read-only variable. You cannot assign a value to
an in parameter, nor can you pass an in parameter as an argument to
another procedure that expects a var, out, or in out argument.
out Indicates that the parameter is used to pass values out of the routine. In
effect, declaring a parameter as out informs the compiler that the
parameter has no initial value, and that assignments to the parameter are
retained by the caller.
in out Indicates that the parameter can both take in values and pass them back
out. An in out parameter is equivalent to a var parameter.
Example
begin
result := length * width
end; { compute_area } { compute_area }
begin
result := result * 2
end; { multiply_by_two } { multiply_by_two }
Program Declarations 87
5
var Parameters
With standard conformance options (-s, -V0, -V1), var parameters are the
same in standard Pascal and Pascal. By default, the Apollo-like var
compatibility approach applies: actual and formal records and arrays should
be of the same type; other types of var must be of the same length.
For example, all pointer types are compatible to univ_ptr, and vice versa.
See “Universal Pointer” on page 42. Subranges -128...127 and 0...127 are
also var-compatible.
Value Parameters
Value parameters are the same in standard Pascal and Pascal.
univ Parameters
The nonstandard univ parameter type is actually a modifier used before data
types in formal parameter lists to turn off type checking for that parameter.
You can use it with any type of parameter except conformant array, procedure,
or function parameters.
You could then call this procedure with a parameter of any type. You should
always declare a univ parameter as either in, out, in out, or var.
type
real_array = array[1..100] of real;
var
n: integer;
begin
for n:= 1 to size do
.
.
.
Type Identifier
In Pascal, a function may represent a structure, such as a set, array, or record.
In standard Pascal, a function can only represent the simple types of value,
ordinal, or real.
where:
• F is the function name
• S1, ..., SN are appropriate component selectors
• E is the result component value
Program Declarations 89
5
Standard Pascal allows assignments to the whole function result variable only,
that is, F:= E, which may not be feasible or efficient enough, since you may
have to declare and initialize extra structured-type variables.
where F is the function. However, sometimes you may want to obtain the
string result by modifying some of the characters of an existing string (variable
or parameter). In the following example, you may want to substitute a string
for the string XX.
program String_Function_Example;
type s1 = array [1..20] of char;
s2 = array [1..2 ] of char;
function f(x:s2):s1;
begin
f := 'The answer: XX miles';
f[13]:=x[1];
f[14]:=x[2];
end;
var r: s2;
s: s1;
begin
r:='12';
s:=f(r);
writeln(s)
end.
for specifying the i'th byte of the function result. This Pascal extension can be
used both for strings and varying strings.
program complex_vectors;
type
complex = record re, im: real end;
compl_vect = array [1..10] of complex;
Options
Pascal supplies the standard forward routine option and the nonstandard
options, extern, external, internal, variable, and nonpascal.
forward
The forward option is the same in Pascal and standard Pascal.
Program Declarations 91
5
internal
The internal option makes the procedure or function local to that module.
Specifying the internal option is the same as declaring the procedure or
function as private. Pascal generates an error message if you attempt to
declare a public procedure or function as internal.
variable
Using the variable option, you can pass a procedure or function a smaller
number of actual arguments than the number of formal arguments defined in
the routine. The actual arguments must match the formal parameters types.
You cannot pass a larger number of actual arguments than formal arguments.
Example
var
price: single;
resident: char;
total: single;
begin
if count = 2 then
calculate := price + tax + shipping_fee
else
calculate := price + shipping_fee
end; { calculate }
Program Declarations 93
5
nonpascal
Pascal supports nonpascal as a routine option when you compile your
program with the –xl option. nonpascal declares non-Pascal routines when
you are porting Apollo DOMAIN programs written in DOMAIN Pascal,
FORTRAN, or C.
nonpascal passes arguments by reference. If the argument is a variable,
nonpascal passes its address. If the argument is a constant or expression,
nonpascal makes a copy on the caller’s stack and passes the address of the
copy.
This chapter describes the built-in procedures and functions Pascal supports.
It starts with two major sections:
The third section, beginning on page 99, lists the nonstandard routines
alphabetically and contains detailed descriptions and examples of each routine.
95
6
Routine Description
addr Returns the address of a variable, constant, function, or procedure.
card Returns the cardinality of a set.
expo Calculates the exponent of a variable.
firstof Returns the first possible value of a type or variable.
in_range Determines whether a value is in the defined integer subrange.
lastof Returns the last possible value of a type or variable.
max Returns the larger of two expressions.
min Returns the smaller of two expressions.
random Generates a random number between 0.0 and 1.0.
seed Resets the random number generator.
sizeof Returns the size of a designated type or variable.
Routine Description
arshft Does an arithmetic right shift of an integer.
asl Does an arithmetic left shift of an integer.
asr Identical to arshft.
land Returns the bitwise and of two integers.
lnot Returns the bitwise not of an integer.
lor Returns the inclusive or of two integers.
lshft Does a logical left shift of an integer.
lsl Identical to lshft.
lsr Identical to rshft.
rshft Does a logical right shift of an integer.
xor Returns the exclusive or of two integers.
Routine Description
concat Concatenates two strings.
index Returns the position of the first occurrence of a string or character
inside another string.
length Returns the length of a string.
stradd Adds a string to another string.
substr Extracts a substring from a string.
trim Removes all trailing blanks in a character string.
Routine Description
append Opens a file for modification at its end.
close Closes a file.
filesize Returns the current size of a file.
flush Writes the output buffered for a Pascal file into the associated
operating system file.
getfile Returns a pointer to the C standard I/O descriptor associated with a
Pascal file.
linelimit Terminates program execution after a specified number of lines has
been written into a text file.
message Writes the specified information on stderr.
open Associates an external file with a file variable.
remove Removes the specified file.
seek Performs random access to a file, changing its current position.
tell Returns the current position of a file.
Routine Description
read and Reads in boolean variables, fixed- and variable-length strings, and
readln enumerated types from the standard input.
reset and Accepts an optional second argument, an operating system file name.
rewrite
write and Outputs enumerated type values to the standard output.
writeln Outputs expressions in octal or hexadecimal.
Allows negative field widths.
Routine Description
argc Returns the number of arguments passed to the program.
argv Assigns the specified program arguments a string variable.
clock Returns the user time consumed by this process.
date Fetches the current date.
discard Explicitly discards the return value of a function.
getenv Returns the value associated with an environment name.
halt Terminates program execution.
null Performs no operation.
pcexit Terminates the program and returns an exit code.
stlimit Terminates program execution if a specified number of statements have
been executed in the current loop
sysclock Returns the system time consumed by this process.
time Retrieves the current time.
trace Prints a stack traceback.
Type transfer Changes the data type of a variable or expression.
wallclock Returns the elapsed number of seconds since
00:00:00 GMT January 1, 1970.
addr
The addr function returns the address of a variable, constant, function, or
procedure.
Syntax
addr(x)
Arguments
x is either a variable, a constant string, a function, or a procedure.
Return Value
The return value of addr is the address in which the variable or a constant
string is stored. For function or procedural arguments, addr returns the
starting address of the function or procedure. In each case, addr returns a
value of type univ_ptr.
Comments
In Pascal, you can apply addr to a variable, function, or procedure with
dynamic extent such as local variables and nested functions or procedures.
Exercise caution in doing so and then dereferencing the resulting pointer value.
In the case of local variables, dereferencing these pointers outside the scope in
which the variable is active results in a meaningless value.
The compiler passes a static link to nested functions and procedures when it
calls them. The compiler does not generate this link when dereferencing
pointer values to procedures or functions. Consequently, Pascal generates a
warning if the argument to addr is any of these objects.
Note – If you use the addr ( ) function, do not use the –H option. The –H
option makes sure that all pointers used point into the heap.
Example
const
name = 'Gail';
type
ptr = ^ integer;
ptr_char = ^ alfa;
var
ptr_address: ptr;
ptr_address_char: ptr_char;
x: integer;
y: integer;
c: alfa;
begin
x := maxint;
append
The append function allows a file to be modified, and sets the current position
to the end of the file.
Syntax
append(file, filename)
Arguments
file is a variable with the text or file data type.
Return Value
append does not return any values.
Comments
For example, this code associates the Pascal file data with the operating system
file, existent:
append(data, 'existent');
Example
The example that follows shows how to use append.
argc
The argc function returns the number of arguments passed to the program.
Syntax
argc
Arguments
argc does not take any arguments.
Return Value
argc returns an integer value.
Comments
The return value of argc is always at least 1, the name of the program.
argc is normally used in conjunction with the built-in procedure, argv. See
the argv listing on page 105.
Example
See the example in the argv listing page 105.
argv
The argv procedure assigns the specified program argument to a string
variable.
Syntax
argv(i, a)
Arguments
i is an integer value.
Return Value
argv returns a string variable.
Comments
argv returns the i'th argument of the current process to the string variable a. i
ranges from 0, the program name, to argc-1.
argc is a predeclared function that tells you how many arguments are being
passed to the program. argv is normally used in conjunction with argc.
Example
var
i: integer32;
name: varying [30] of char;
begin
{ Argument number 0 is the name of the program. }
argv(0, name);
writeln('The name of the program is ', name, '.');
i := 1;
while i <= argc - 1 do begin
argv(i, name);
writeln('Argument number ', i: 1, ' is ', name, '.');
i := i + 1
end
end. { argv_example }
arshft
The arshft function does an arithmetic right shift of an integer value.
Syntax
arshft(num, sh)
Arguments
num and sh are integer expressions.
Return Value
arshft returns a 32-bit integer value.
Comments
arshft shifts the bits in num sh places to the right. arshft preserves the sign
bit of num. arshft does not wrap bits around from left to right. The sign bit
is the most significant (leftmost) bit in the number. Pascal uses two's
complement to represent negative integers. For example, -8 as a 16-bit integer
is represented as:
1111 1111 1111 1000
Example
const
SIZE = 8;
var
i: integer32;
i32: integer32;
loop: integer32;
begin
write('Enter a positive or negative integer: ');
readln(i);
for loop := 1 to SIZE do begin
i32 := arshft(i, loop);
write('Arithmetic right shift ', loop: 2);
writeln(' bit(s): ', i32 hex)
end
end. { arshft_example }
asl
The asl function does an arithmetic left shift of an integer value.
Syntax
asl(num, sh)
Arguments
num and sh are integer expressions.
Return Value
asl returns a 32-bit integer value.
Comments
asl shifts the bits in num sh places to the left. asl preserves the sign bit of
num and does not wrap bits from left to right.
Example
const
SIZE = 8;
var
i: integer32;
i32: integer32;
loop: integer32;
begin
write('Enter a positive or negative integer: ');
readln(i);
for loop := 1 to SIZE do begin
i32 := asl(i, loop);
write('Arithmetic left shift ', loop: 2);
writeln(' bit(s): ', i32 hex)
end
end. { asl_example }
asr
The asr function is identical to the arshft function. See the arshft listing.
card
The card function returns the number of elements in a set variable.
Syntax
card(x)
Arguments
x must be a set variable.
Return Value
card returns an integer value.
Comments
card returns the number of elements in the actual set variable, not the size of
the set type.
Example
var
pri: primary_colors;
pos: possibilities;
cap: capital_letters;
dig: digits;
begin
pri := [red, yellow, blue];
pos := [true, false];
cap := ['A'..'Z'];
dig := [0..100];
writeln('There are ',card(pri): 4, ' primary colors.');
writeln('There are ',card(pos): 4, ' possibilities.');
writeln('There are ',card(cap): 4, ' capital letters.');
writeln('There are ',card(dig): 4, ' digits.')
end. { card_example }
clock
The clock function returns the user time consumed by the process.
Syntax
clock
Arguments
clock does not take any arguments.
Return Value
clock returns an integer value.
Comments
clock returns the user time in milliseconds.
See also the sysclock function, which returns the system time the process
uses.
Example
const
DISK = 16;
var
num: array [1..3] of integer;
counts: integer32;
before_user: integer;
before_sys: integer;
after_user: integer;
after_sys: integer;
var
o: integer;
begin
if number = 1 then begin
num[f] := num[f] - 1;
num[t] := num[t] - 1;
counts := counts + 1
end else begin
o := 6 - (f + t);
moves(number - 1, f, o);
moves(1, f, t);
moves(number - 1, o, t)
end
end; { moves } { moves }
close
The close procedure closes a file.
Syntax
close(file)
Arguments
file is a file having the text or file data type.
Return Value
close does not return any values.
Comments
close closes the open file named file. close is optional; Pascal closes all files
either when the program terminates or when it leaves the procedure in which
the file variable is associated with the open file.
Pascal generates a runtime error if file is not an open file. You can trap this
error with the I/O error recovery mechanism, described in “I/O Error
Recovery” on page 214.
In Pascal, you cannot close the predeclared files input and output. If you
redirect input or output, the associated streams are automatically closed.
See also the open, reset, and rewrite procedures, which open a file.
Example
See the example in the open listing in this chapter.
concat
The concat function returns the concatenation of two strings.
Syntax
concat(str1, str2)
Arguments
str1 is a variable-length string, a character array, or a character-string constant.
Return Value
concat returns a variable-length string.
Comments
concat returns a concatenation of str1 and str2. You can concatenate any
combination of varying, array of char, constant strings, and single characters.
The string plus (+) operator returns the same result as the concat function.
If the resulting string is longer than the maximum length of the destination
varying string, it is truncated to this maximum length. If the resulting string is
longer than 65,535 characters, it is truncated to this length.
Example
begin
writeln(concat(color, 'bird' + '.'));
end.
date
The date procedure takes the current date (as assigned when the operating
system was initialized) and assigns it to a string variable.
Syntax
date(a)
Arguments
a is a variable that can be either a character array that is 8 elements long for the
"C" locale, or a variable-length string.
Return Value
date returns a character string in the form traditional for a given locale. For
the "C" locale, the form is mm-dd-yy, where dd is the day, mm is the month,
and yy is the year.
Comments
date puts a zero in front of the day and the year, so that they always consist of
two digits.
Example
var
s1: alfa;
s2: array[1..8] of char;
s3: array[89..96] of char;
s4: varying[100] of char;
begin
date(s1);
date(s2);
date(s3);
date(s4);
writeln('The date is ', s1, '.');
writeln('The date is ', s2, '.');
writeln('The date is ', s3, '.');
writeln('The date is ', s4, '.');
end.
discard
The discard procedure removes the value of an expression.
Syntax
discard(expr)
Arguments
expr is any expression including a function call.
Return Value
discard does not return any values.
Comments
Use discard to call a function or evaluate an expression whose value you do
not need to continue program execution. For example, you can use discard
to execute a function whose return value you do not need.
Example
const
RATE = 0.15;
DISC_AMOUNT = 100.00;
var
amount: single;
discount: single;
begin
compute := amount * RATE
end; { compute }
expo
The expo function calculates the integer-valued exponent of a specified
number.
Syntax
expo(x)
Arguments
x is either a real or integer value.
Return Value
expo returns an integer value.
Comments
expo returns an integer that represents the integer-valued exponent of a real
number.
Example
const
MAX = 10;
var
i: integer;
r: real;
begin
writeln(' x r := exp(x) expo(r)');
writeln(' - ----------- -------');
for i := 1 to MAX do begin
r := exp(i);
writeln(i: 2, ' ', r, ' ', expo(r))
end
end. { expo_example }
filesize
The filesize function returns the size of a given file.
Syntax
filesize(file)
Arguments
file is a variable with the text or file data type.
Return Value
filesize returns an integer value.
Comments
The argument can be either a text file of text type, or a binary file of a certain
file of T type. It must be associated with an open file, otherwise an error
occurs.
For a text file, filesize returns the number of bytes in the file.
Example
firstof
The firstof function returns the value of the lower bound when its
argument is or has an ordinal type. For array types, firstof returns the
lower bound for the subrange defining the array index. For set types, it
returns the lower bound of the set base type.
Syntax
firstof(x)
Arguments
x is either a variable, a constant, an expression, or the name of a user-defined
or predeclared Pascal data type. x cannot be a record, a file, a pointer type, a
conformant array, a procedure or function parameter, or a string literal.
Return Value
The return value depends on the type that x is.
Comments
Pascal follows the rules in Table 6-9 when returning the value of x.
Example
See the examples that follow.
const
dollars_per_tourist = 100;
type
continents = (North_America, South_America, Asia, Europe,
Africa, Australia, Antarctica);
var
i: continents;
major_targets: array [continents] of integer :=
[20, 3, 15, 25, 5, 1, 0];
planned_targets: array [continents] of integer := [* of 0];
begin
for i := firstof(planned_targets) to
lastof(planned_targets) do begin
planned_targets[i] := major_targets[i] * dollars_per_tourist
end;
end. { firstof_example }
flush
The flush procedure writes the output buffer for the specified Pascal file into
the associated file.
Syntax
flush(file)
Arguments
file is a file having the text or file data type.
Return Value
flush does not return any values.
Comments
The flush procedure causes the compiler to write all characters buffered for
output to the specified file.
For example, in the following code fragment, the compiler writes the output
integer i to the file f when it encounters flush:
for i := 1 to 5 do begin
write(f,i);
Compute a lot with no output
end;
flush(f);
flush does not append a newline character after writing the data. See also the
output procedures, message, write, and writeln.
Example
const
NAME = 'flush.txt';
var
i: integer;
f1, f2: text;
procedure read_file;
var
i: integer;
begin
reset(f2, NAME);
writeln('Beginning of file.');
while not eof(f2) do begin
while not eoln(f2) do begin
read(f2, i);
writeln(i)
end;
readln(f2)
end;
writeln('End of file.');
writeln
end; { read_file }
flush.p (Screen 1 of 2)
flush(f1);
flush.p (Screen 2 of 2)
Beginning of file.
1
2
3
4
5
6
7
8
9
10
End of file.
getenv
The getenv function returns the value associated with an environment name.
Syntax
getenv(string, string_variable)
Arguments
string is either a constant string, a variable-length string, or a character array.
string_variable is a variable-length string or a character array.
Return Value
getenv returns a variable-length string or a character array.
Comments
The variable string is an environment name. Pascal returns the value for the
environment name through the parameter, string_variable.
string must match the environment exactly, and trailing blanks are significant.
If string is a character array, you may want to use the trim function.
If there are no environment names with the value string, the value of
string_variable is the null string if string_variable is a variable-length string. If
string_variable is a character array, it is padded with blanks.
Example
var
namev: varying [10] of char := 'EDITOR';
names: array [1..10] of char := 'EDITOR';
valv: varying [20] of char;
begin
getenv(namev, valv);
writeln(namev, ' = ', valv);
getenv(trim(names), valv);
writeln(names, ' = ', valv)
end. { getenv_example }
getfile
The getfile function returns a pointer to the C standard I/O descriptor
associated with a Pascal file.
Syntax
getfile(file)
Arguments
file is a file having the text or file data type. file must be associated with an
open file; otherwise, getfile returns nil.
Return Value
getfile returns a value of type univ_ptr.
Comments
You can use the result of getfile for files opened with either the reset,
rewrite, or open procedures, placing the return value as a parameter to a C
I/O routine. Use extreme caution when you call getfile; directly calling C
I/O routines circumvents bookkeeping data structures in the Pascal I/O
library.
As a general rule, calling C routines for writing is safe. Using the return value
for calling C routines for reading may cause subsequent eoln, eof, or readln
calls to produce errors for that file.
Example
type
char_array = array [1..30] of char;
var
f: text;
cfile: univ_ptr;
halt
The halt procedure terminates program execution.
Syntax
halt
Arguments
halt does not take any arguments.
Return Values
halt does not return any values.
Comments
You can use halt anywhere in a program to terminate execution. When
execution of a program encounters a halt, it prints the following message:
Example
var
x, y: integer;
begin
if n = 0 then
factorial := 1
else
factorial := n * factorial(n - 1)
end; { factorial } { factorial }
in_range
The in_range function checks if a value is in the defined subrange.
Syntax
in_range(x)
Arguments
x is an integer, boolean, character, enumerated, or subrange data type.
Return Value
in_range returns a boolean value.
Comments
in_range returns true if x is in the defined range, false if x is outside the
range.
in_range is useful for doing a runtime check to see if x has a valid value.
in_range is especially helpful for checking enumerated and subrange types.
However, this feature does not work for 32-bit integer values.
If you compile your program with the –C option, the compiler also generates
code that does range checking. However, if the variable is out of range, the
program terminates. By using in_range instead, you can control subsequent
execution of your program.
Example
type
positive = 1..maxint;
var
base, height: positive;
area: real;
begin
write('Enter values for triangle base and height: ');
readln(base, height);
if in_range(base) and in_range(height) then begin
area := base * height / 2;
writeln('Area is ', area: 5: 2, '.')
end else
writeln('Cannot compute negative areas.')
end. { in_range_example }
index
The index function returns the position of the first occurrence of a string or
character within another string.
Syntax
index(target_string, pattern_string)
Arguments
target_string is a constant string, variable-length string, or an array of character.
Return Value
index returns an integer value that represents the position of the first
occurrence of pattern_string within target_string. If the first occurrence is at the
starting position of the original string, the returned index value is 1.
Comments
The leftmost occurrence of the pattern-string is considered the first occurrence.
Example
See the example that follows.
const
MAX = 20;
STRING = 'FOO';
type
char_array = varying [MAX] of char;
var
s1: char_array := 'INDEX_EXAMPLE';
s2: char_array := 'EXAMPLE';
i: integer16;
begin
if index = 0 then begin
write('The string ', s2, ' is not');
writeln(' in the string ', s1, '.')
end else begin
write('The string ', s2, ' is at index ', i: 1);
writeln(' in the string ', s1, '.')
end
end; { print } { print } { print }
land
The land function returns the bitwise and of two integer values.
Syntax
land(int1, int2)
Arguments
int1 and int2 are integer expressions.
Return Value
land returns an integer value.
Comments
land performs a bit-by-bit and operation, as shown in Table 6-10.
If int1 and int2 are different size integers, Pascal converts the smaller integer to
the larger integer before it performs the land operation.
land produces the same results as the bitwise operator &. Do not confuse
land with the boolean operator and, which finds the logical and of two
boolean expressions.
Example
var
i: integer32;
begin
write(' Decimal : ', intval, ' Binary : ');
for i := 31 downto 0 do begin
if lsr(intval, i) mod 2 = 0 then
write('0')
else
write('1')
end;
writeln
end; { BinaryOutput }
var
ival1, ival2: integer32;
begin
ival1 := 2#00000000000000000000000000001111;
ival2 := 2#00000000000000000000000011111111;
writeln('IVAL1');
BinaryOutput(ival1);
writeln('IVAL2');
BinaryOutput(ival2);
writeln('LNOT(IVAL1)');
BinaryOutput(lnot(ival1));
writeln('LAND(IVAL1,IVAL2)');
BinaryOutput(land(ival1, ival2));
writeln('LOR(IVAL1,IVAL2)');
BinaryOutput(lor(ival1, ival2));
writeln('XOR(IVAL1,IVAL2)');
BinaryOutput(xor(ival1, ival2))
end. { land_example }
lastof
The lastof function returns the value of the upper bound when its argument
is or has an ordinal type. For array types, lastof returns the upper bound for
the subrange defining the array index. For set types, it returns the upper
bound of the set base type.
Syntax
lastof(x)
Arguments
x is either a variable, a constant, an expression, or the name of a user-defined
or predeclared Pascal data type. x cannot be a record, a file, a pointer type, a
conformant array, a procedure or function parameter, or a string literal.
Return Value
When x is an ordinal type, a constant, an expression, or variable, the value
lastof returns has the same data type as its argument.
When x is an array, the value lastof returns has the same data type as the
type of the array index.
Comments
Pascal follows the rules in Table 6-11 when returning the value of x.
Example
See the example under firstof on page 126.
length
The length function returns the length of a string.
Syntax
length(str)
Arguments
str is a variable-length string, a character array, or a character-string constant.
Return Value
length returns an integer value.
Comments
length returns a value that specifies the length of str.
Example
var
s1: array [1..15] of char;
s2: varying [20] of char;
begin
s1 := 'San Francisco ';
s2 := 'California';
writeln('The length of string one is ', length(s1): 2, '.');
writeln('The length of string two is ', length(s2): 2, '.');
writeln('The combined length is ', length(s1 + s2): 2, '.')
end. { length_example }
linelimit
The linelimit procedure terminates execution of a program after a specified
number of lines has been written into a text file.
Syntax
linelimit(file, n)
Arguments
file is a file having the text or file data type.
Return Value
linelimit does not return any values.
Comments
linelimit terminates program execution if more than n lines are written to
file f. If n is less than zero, no limit is imposed.
linelimit has no effect unless you compile your program with the –C
option.
Example
const
FILE = 'linelimit.dat';
var
infile: text;
error: integer32;
name: array [1..20] of char;
begin
open(infile, FILE, 'unknown', error);
rewrite(infile, FILE);
if error = 0 then begin
writeln('Enter the names of your children.');
writeln('The last entry should be "0".');
repeat
readln(name);
writeln(infile, name);
linelimit(infile, 10)
until name = '0';
close(infile)
end else begin
writeln('Difficulty opening file.');
writeln('Error code = ', error, '.')
end
end. { linelimit_example }
lnot
The lnot function returns the bitwise not of an integer value.
Syntax
lnot(int)
Arguments
int is an integer expression.
Return Value
lnot returns an integer value.
Comments
lnot performs a bit-by-bit not operation, as shown in Table 6-12.
lnot produces the same results as the bitwise operator ~. Do not confuse
lnot with the boolean operator not, which evaluates the logical not of a
boolean expression.
Example
See the example under land on page 142.
lor
The lor function returns the inclusive or of two integer values.
Syntax
lor(int1, int2)
Argument
int1 and int2 are integer expressions.
Return Value
lor returns an integer value.
Comments
lor performs an inclusive or, as shown in Table 6-13.
If int1 and int2 are different size integers, Pascal converts the smaller integer to
the larger integer before it performs the lor operation.
lor produces the same results as the bitwise operators ! and |. Do not
confuse lor with the boolean operator or, which evaluates the logical or of
a boolean expression.
Example
See the example under land on page 142.
lshft
The lshft function does a logical left shift of an integer value.
Syntax
lshft(num, sh)
Argument
num and sh are integer expressions.
Return Value
lshft returns a 32-bit integer value.
Comments
lshft shifts all bits in num sh places to the left. lshft does not wrap bits
from the left to right. The value lshft returns is machine-dependent and is
unspecified unless 0 <= sh <= 32.
Do not confuse lshft with the arithmetic left shift functions which preserve
the sign bit.
const
SIZE = 8;
var
i: integer32;
i32: integer32;
loop: integer32;
begin
write('Enter a positive or negative integer: ');
readln(i);
for loop := 1 to SIZE do begin
i32 := lshft(i, loop);
write('Logical left shift ', loop: 2);
writeln(' bit(s): ', i32 hex)
end
end. { lshft_example }
lsl
The lsl function is identical to the lshft function. See the lshft listing on
page 151.
lsr
The lsr function is identical to the rshft function. See the rshft listing on
page 171.
max
The max function evaluates two scalar expressions and returns the larger one.
Syntax
max(exp1, exp2)
Arguments
exp1 and exp2 are any valid scalar expressions that are assignment-compatible.
Return Value
max returns the same or the converted type of exp1 and exp2.
Example
var
smallest_odd: integer := 501;
largest_even: integer := 0;
number, counter: integer;
begin
writeln('Please enter 10 integers between 0 and 501:');
for counter := 1 to 10 do begin
read(number);
if (number < 0) or (number > 501)
then writeln ('The number is out of range ')
else if odd(number)
then smallest_odd := min(number, smallest_odd)
else
largest_even := max(number, largest_even)
end;
writeln('The smallest odd number is ', smallest_odd: 1, '.');
writeln('The largest even number is ', largest_even: 1, '.')
end. { max_example }
message
The message procedure writes the specified information on stderr (usually
the terminal).
Syntax
message(x1, ..., xN)
Arguments
x is one or more expressions separated by commas. x can be a variable,
constant, or expression of a type that write accepts (such as integer, real,
character, boolean, enumerated, or string). x cannot be a set variable.
Return Value
message does not return any values.
Comments
message is an output procedure similar to write and writeln. Whereas
write and writeln send the output to standard output or the specified file,
message sends the output to standard error. message also appends a
carriage return to the message.
message flushes all buffers both before and after writing the message.
Example
begin
writeln('This message will go to standard output.');
message('This message will go to standard error.')
end. { message_example }
min
The min function evaluates two scalar expressions and returns the smaller one.
Syntax
min(exp1, exp2)
Arguments
exp1 and exp2 are any valid scalar expressions that are assignment-compatible.
Return Value
min returns the same or the converted type of exp1 and exp2.
Comments
See also the max listing on page 153.
Example
See the example under the max listing on page 153.
null
The null procedure performs no operation.
Syntax
null
Arguments
null does not take any arguments.
Return Value
null does not return any values.
Comments
null does absolutely nothing; it is useful as a placeholder. For example,
suppose you are developing a program, and you are uncertain about a
particular case statement, you could put null in place of the case statement,
then replace it later with an actual function or procedure.
open
The open procedure associates an external file with a file variable.
Syntax
open(file, pathname, history, error, buffer)
Arguments
open takes the following arguments:
• file is a variable having the text or file data type.
• pathname is a string constant or string variable.
• history is a string variable.
• error is an integer32 variable. This argument is optional.
• buffer is an optional integer variable. This argument is currently ignored.
Return Value
open does not return any values.
Comments
open associates the permanent file file with a file variable for reading or
writing. open does not actually open the file; you must call reset or
rewrite before reading or writing to that file.
'new' Associates the operating system file with a new file. The compiler
generates an error if the file already exists.
'old' Associates the operating system file with an existing file. The
compiler generates an error if the file does not exist. This option
first tries to open the file for writing. Failing to do so, it tries to
open it for reading only.
'unknown' Searches for an existing file and associate it with the operating
system file. The compiler creates the file if it does not exist.
Pascal returns an integer error code through error, as shown in Table 6-14.
Number Description
0 open is successful.
1 File not specified on the command-line. For example, this error is
generated for the following line when argument one is not specified:
open(infile,'^1','new',Error);
2 Unable to open file.
3 Invalid history specified. history must be either 'new', 'old', or
'unknown'.
Pascal automatically closes all open files when your program terminates or
when the program exits the scope in which the file variable for the open file is
allocated. See also the close, reset, and rewrite procedures.
const
name_of_file = 'open1.txt';
file3 = '*Enter_a_filename-- ';
type
char_array = varying [50] of char;
var
infile: text;
error: integer32;
name: char_array;
begin
{ Open an existing file. }
open(infile, name_of_file, 'old', error);
if error = 0 then begin
writeln('Opened ', name_of_file, ' for reading.');
close(infile)
end else
writeln('Error opening file', name_of_file, error);
pcexit
The pcexit function:
• Checks whether any imposed statement count has been exceeded.
• Calls the ieee_retrospective ( ) routine. See the Solaris
documentation for details.
• Terminates the program with the specified return value (similar to the C
exit() function).
Syntax
pcexit(x)
Arguments
x is an integer variable or constant.
Return Value
pcexit does not return any values.
Comments
The C function exit(3C) calls any functions registered through the
atexit(3C) function in the reverse order of their registration.
random
The random function generates a random number between 0.0 and 1.0.
Syntax
random(x)
Arguments
x has no significance and is ignored.
Return Value
random returns a real value.
Comments
random generates the same sequence of numbers each time you run the
program. See the seed function on page 172 to reseed the number generator.
Example
var
i: integer;
x: integer;
begin
writeln('These numbers were generated at random:');
for i := 1 to 5 do begin
write(trunc(random(x) * 101))
end;
writeln
end. { random_example }
Syntax
read(file, var1 ..., varN);
Arguments
file is an optional variable having either the text or file data type.
Return Value
read and readln do not return any values.
Comments
If var is a variable-length string, read and readln try to read in as many
characters as indicated by the current length, up to the first newline character.
read and readln do not pad the string with blanks if the length of the string
is less than the current length.
If var is an enumerated type, read and readln attempt to read a value that is
included in the type definition. If the value is not in the type definition, the
compiler terminates program execution and prints the following error
message:
You can trap this error with the I/O error recovery mechanism, described in
“I/O Error Recovery” on page 214. Using read or readln in the block of a
function in the form:
read (..., f, ...)
Example
type
gem_cuts = (marquis, emerald, round, pear_shaped);
var
x: gem_cuts;
gem: varying [10] of char;
gift: boolean;
begin
write('Enter type of gem: ');
readln(gem);
write('Enter cut: ');
write('marquis, emerald, round, pear_shaped: ');
readln(x);
write('Enter true if this a gift, false if it is not: ');
readln(gift);
write('You have selected a ', gem);
writeln(' with a ', x, ' cut.');
if gift then
writeln('We will gift wrap your purchase for you.')
end. { read_example }
remove
The remove procedure removes the specified file.
Syntax
remove(file)
Arguments
file is either a fixed- or variable-length string that indicates the name of the file
to be removed. file cannot be a text or file variable.
Return Value
remove does not return any values.
Comments
Pascal generates an I/O error if the file does not exist. You can trap this error
with the I/O error recovery mechanism, described in “I/O Error Recovery” on
page 214.
Example
var
name: varying [10] of char;
begin
if argc <> 2 then
writeln('Usage is : rm <file>')
else begin
argv(1, name);
remove(name)
end
end. { remove_example }
reset
Pascal supports an optional second argument to the reset procedure. This
argument gives an operating system file name.
Syntax
reset(file, filename)
Arguments
file is a variable having the text or file data type.
Return Value
reset does not return any values.
Comments
reset gives you permission to read from the file, but not to write to the file.
In standard Pascal, reset takes only one argument, a file variable. In Pascal,
reset can take an optional second argument, an operating system file name.
If you give the optional file name, the compiler opens the file with that name
on the current path and associates it with the given file variable.
For example, this code associates the Pascal file data with the operating
system file primes:
reset(data, 'primes');
reset does an implicit close on the file, hence you can reuse its file variable
with a different file. Similarly, if input or output is reset, the current
implementation of the product also implicitly closes stdin and stdout.
reset normally generates an error and halts if the file specified in the two
argument form does not exist. You can trap this error with the I/O error
recovery mechanism, described in “I/O Error Recovery” on page 214.
See also the section on “rewrite,” which opens a file for writing.
Example
See the example in the rewrite listing that follows.
rewrite
Pascal supports an optional second argument to the rewrite procedure. This
argument gives an operating system file name.
Syntax
rewrite(file, filename)
Arguments
file is a variable having the text or file data type.
Return Value
rewrite does not return any values.
Comments
rewrite gives you permission to modify a file.
• In standard Pascal, rewrite takes only one argument—a file variable.
• In Pascal, rewrite can take an optional second argument, an operating
system file name.
In Pascal, if you give the optional file name, the compiler opens the file with
that name on the current path and associates it with the given file variable. For
example, this code associates the Pascal file data with the operating system
file primes:
rewrite(data, 'primes');
If the file variable is output, and the second argument is not given, Pascal
creates a temporary file, but does not delete it after the program exits.
rewrite does an implicit close on the file, thus you can reuse its file variable
with a different file.
See also the section on “reset,” which opens a file for reading.
Example
const
MAX = 80;
var
f: text;
line: varying [MAX] of char;
begin
rewrite(f, 'poem.txt');
write('Enter a line of text.');
writeln(' Hit Control-D to end the job.');
while not eof do begin
readln(line);
writeln(f, line)
end;
close(f);
writeln;
writeln;
writeln('These are the lines of text you input:');
reset(f, 'poem.txt');
while not eof(f) do begin
readln(f, line);
writeln(line)
end;
close(f)
end. { rewrite_example }
rshft
The rshft function does a logical right shift of an integer value.
Syntax
rshft(num, sh)
Arguments
num and sh are integer expressions.
Return Value
rshft returns a 32-bit integer value.
Comments
rshft shifts the bits in num sh spaces to the right. rshft does not preserve
the sign bit (leftmost) bit of a number and does not wrap bits from right to left.
The value rshft returns is machine-dependent, and is unspecified unless
0 <= sh <= 32. Do not confuse rshft with the arithmetic right shift
functions asr and arshft, which preserve the sign bit.
const
SIZE = 8;
var
i: integer32;
i32: integer32;
loop: integer32;
begin
write('Enter a positive or negative integer: ');
readln(i);
for loop := 1 to SIZE do begin
i32 := rshft(i, loop);
write('Logical right shift ', loop: 2);
writeln(' bit(s): ', i32 hex)
end
end. { rshft_example }
seed
The seed function reseeds the random number generator.
Syntax
seed(x)
Arguments
x is an integer value.
Return Value
seed returns an integer value.
Comments
seed sets the random number generator to x and returns the previous seed. If
you do not reseed the random number generator, the random function returns
the same sequence of random numbers each time you run the program. To
produce a different random number (sequence each time the program is run),
set the seed with the following statement:
x := seed(wallclock);
Example
See the example that follows.
var
i: integer;
x: integer;
begin
x := seed(wallclock);
writeln('These numbers were generated at random:');
for i := 1 to 5 do begin
write(trunc(random(i) * (i * 101)))
end;
writeln
end. { seed_example }
seek
The seek procedure changes the current position in the file.
Syntax
seek(file, pos)
Arguments
file is a variable with the text or file data type.
Return Value
seek does not return any values.
Comments
The seek procedure is a facility to support random access input/output. It
changes the position of a given file that is open for reading or writing.
You can use seek with text files of text type, or binary files of a certain file
of T type.
For a binary file of type file of T, the argument pos denotes the number of
the element of type T, which becomes the new position of file. Elements are
numbered from 0. The argument pos can have an arbitrary non-negative value.
If file is open for writing, and pos exceeds the size of the file, the file is
appended by the corresponding number of elements of type T with undefined
values. For example, if filesize(f) = 0, then after seek(f,100) and
write(f,x), the result is: filesize(f) = 101.
If file is open for reading, seek does not detect an error in seeking an element
with a non-existing number. The compiler may detect this error later, however,
when it performs the read procedure.
For a text file, you can use seek only in the following forms:
That is, seek can only set the current position to the beginning of the file or
have it stay “as is,” otherwise an error occurs. Hence, the only correct way of
processing a text file in Pascal is reading or writing it successively, line by line.
Example
sizeof
sizeof returns the number of bytes the program uses to store a data object.
Syntax
sizeof(x, tag1, ... tagN)
Arguments
x is any predeclared or user-defined Pascal data type, a variable, a constant, or
a string.
Return Value
sizeof returns an integer value.
Comments
sizeof returns the number of bytes in the data object x. tags correspond to
the fields in a variant record. tags are effectively ignored because Pascal
allocates records according to the largest variant.
You cannot use sizeof to determine the size of a conformant array parameter
because the array size is not known until runtime. The difference between the
size of a constant string and that of a varying string variable to which the
string is assigned. For example:
sizeof ('') = 0
Example
const
MAX = 5;
type
subB = false..true;
sub1 = 0..7;
sub2 = 0..127;
sub3 = 0..255;
color1 = (re, gree, blu, whit);
color2 = (red, green, blue, white, orange, purple, black);
rec_type =
record
i: integer;
ar: array [1..MAX] of single;
d: double
end;
var
b: boolean;
c: char;
f: text;
i: integer;
i16: integer16;
i32: integer32;
s: shortreal;
r: real;
l: longreal;
rec: rec_type;
u: univ_ptr;
begin
writeln('The size of boolean is ', sizeof(b), '.');
writeln('The size of char is ', sizeof(c), '.');
writeln('The size of color1 is ', sizeof(color1), '.');
writeln('The size of color2 is ', sizeof(color2), '.');
writeln('The size of file is ', sizeof(f), '.');
writeln('The size of integer is ', sizeof(i), '.');
writeln('The size of integer16 is ', sizeof(i16), '.');
writeln('The size of integer32 is ', sizeof(i32), '.');
writeln('The size of longreal is ', sizeof(l), '.');
writeln('The size of shortreal is ', sizeof(s), '.');
writeln('The size of real is ', sizeof(r), '.');
writeln('The size of rec_type is ', sizeof(rec_type), '.');
writeln('The size of rec_type.ar is ', sizeof(rec.ar), '.');
writeln('The size of subB is ', sizeof(subB), '.');
writeln('The size of sub1 (8) is ', sizeof(sub1), '.');
writeln('The size of sub2 (128) is ', sizeof(sub2), '.');
writeln('The size of sub3 (256) is ', sizeof(sub3), '.');
writeln('The size of univ_ptr is ', sizeof(u), '.')
end. { sizeof_example }
stlimit
The stlimit procedure terminates program execution if a specified number
of statements have been executed in the current loop.
Syntax
stlimit(x)
Arguments
x is an integer value.
Return Value
stlimit does not return any values.
Comments
To use stlimit, you must include the following code in your source program:
{$p+}
When you call stlimit, it tests if x number of statements have been executed
in the current loop. If the number of statements executed equals or exceeds x,
stlimit stops the program, dumps core, and prints the following message:
To check the statement limit after each statement, you can turn on runtime
checks using the –C command-line option or the C or t program text options.
When runtime checks are turned on and the compiler encounters a stlimit
statement, the compiler inserts a statement limit check after each subsequent
statement.
Example
begin
repeat
writeln('Hello.');
stlimit(10)
until false
end. { stlimit_example }
stradd
The stradd procedure adds a string to another string.
Syntax
stradd(strdest, strsrc)
Arguments
strdest is a variable-length string.
Return Value
stradd does not return any values.
Comments
stradd adds strsrc to strdest, and is a more efficient operator for the
concatenation of strings. Use stradd when a string is constructed by multiple
concatenation, with other strings to its end.
Example
begin
stradd(greeting, ',');
stradd(greeting, ' world');
stradd(greeting, '!');
writeln(greeting);
end.
substr
The substr function takes a substring from a string.
Syntax
substr(str, p, n)
Arguments
str is a variable-length string, a character array, or a character-string constant.
p is a positive integer.
Return Value
substr returns a variable-length string.
Comments
substr returns a substring beginning at position p and continuing for n
characters. If the values of either p or n indicate a character outside the
bounds of the string size, Pascal returns a null string.
Example
var
string1: array [1..15] of char;
string2: varying [25] of char;
begin
string1 := 'Paris, Texas';
string2 := 'Versailles, France';
write(substr(string1, 1, 6));
writeln(substr(string2, 12, 7))
end. { substr_example }
sysclock
The sysclock function returns the system time consumed by the process.
Syntax
sysclock
Arguments
sysclock does not take any arguments.
Return Value
sysclock returns an integer value.
Comments
sysclock returns the system time in milliseconds. See also the clock
function, which returns the user time the process consumes.
Example
See the example in the clock listing earlier in this chapter.
tell
The tell function returns the current position of a given file.
Syntax
tell(file)
Arguments
file is a variable with the text or file data type.
Return Value
tell returns an integer value.
Comments
The argument can be either a text file of text type, or a binary file of a certain
file of T type. It must be associated with an open file, otherwise an error
occurs.
For a text file, the tell function returns the byte number that corresponds to
the current position in the file.
For a binary file of type file of T, the tell function returns the number of
the element of type T that corresponds to the current position in the file.
Elements are numbered from 0.
Example
time
The time procedure retrieves the current time.
Syntax
time(a)
Arguments
a is a variable that can be either a character array that is 8 elements long for the
"C" locale, or a variable-length string.
Return Value
time returns a character string in the form traditional for a given locale. For
the "C" locale, the form is hh:mm:ss, where hh is the hour (0 through 23); mm
is the minutes (0 through 59); and ss is the seconds (0 through 59).
Comments
time uses a 24-hour clock. It puts a zero in front of the hours, minutes, and
seconds, so that they always consist of two digits.
Example
var
s1: alfa;
s2: array[1..8] of char;
s3: array[89..96] of char;
s4: varying[100] of char;
begin
time(s1);
time(s2);
time(s3);
time(s4);
writeln('The time is ', s1, '.');
writeln('The time is ', s2, '.');
writeln('The time is ', s3, '.');
writeln('The time is ', s4, '.');
end.
trace
The trace routine prints stack traceback without terminating a program.
Syntax
trace
Arguments
trace does not take any arguments.
Return Value
trace does not return any values.
Comments
You can use the trace routine for debugging. This routine prints stack
traceback information to a file without terminating your program. The name
of the traceback file is p.trace, where p is the name of your executable. For
example, if the executable is called a.out, then the name of the traceback file
is a.out.trace.
The trace routine can be called several times during program execution, if
necessary. In this case, traceback information is appended to the traceback file.
The trace routine uses dbx, so be sure that dbx is in your path.
To print the traceback output in a clearer format, use the -g option to compile
your program.
Example
begin
subr(5);
end.
trim
The trim function removes the trailing blanks in a character string.
Syntax
trim(input_string)
Arguments
input_string is a constant string, a variable-length string, a character array, or a
character.
Return Value
trim returns a variable-length string equal to the input string without any
trailing blanks. If input_string is a null string or contains only blanks, trim
returns a null string of length 0.
Comments
trim has no effect if its result value is assigned to a fixed-length character
string variable. Fixed-length characters are always padded with blanks during
assignments.
Example
begin
l := trim(st1) + trim(st2) + trim(st3) + trim(c1);
writeln(l, length(l));
l := substr(trim(st1) + trim(st2) + trim(st3), 3, 5);
writeln(l, length(l));
l := trim(v1) + trim(TEN) + trim(v2) + trim(v3) + trim(st1)
+ trim(st2) + trim(st3);
writeln(l, length(l))
end. { trim_example }
Type Transfer
The type transfer function changes the data type of a variable, constant, or
expression.
Syntax
transfer_function(x)
Arguments
transfer_function is a predeclared or user-defined Pascal data type.
Return Value
A type transfer function returns its argument unchanged in internal value, but
with a different apparent type.
Comments
Suppose your program contains the following data type declarations:
var
x: integer32;
y: single;
y := single(x);
The type transfer functions copy, but do not convert, a value. Do not confuse
the type transfer functions with functions that actually convert the value of the
variable, such as ord, chr, and trunc.
Example
type
range = 65..90;
var
i: range;
c: char;
begin
for i := firstof(i) to lastof(i) do begin
write('The character value of ', i: 1);
writeln(' is ', char(i), '.')
end
end. { type_transfer_example }
wallclock
The wallclock function returns the elapsed number of seconds since
00:00:00 GMT January 1, 1970.
Syntax
wallclock
Arguments
wallclock does not take any arguments.
Return Value
wallclock returns an integer value.
Comments
wallclock can be used with the seed function to generate a random number.
It can also be used to time programs or parts of programs.
Example
See the example that follows.
const
NTIMES = 20; { Number of times to compute Fib value. }
NUMBER = 24; { Biggest one we can compute with 16 bits. }
var
start: integer;
finish: integer;
i: integer;
value: integer;
begin
if number > 2 then
fib := fib(number - 1) + fib(number - 2)
else
fib := 1
end; { fib }
Syntax
write(file, exp1:width ..., expN:width)
Arguments
file is a variable having either the text or file data type. file is optional; it
defaults to output.
Return Value
write and writeln do not return any values.
Comments
If exp is an enumerated type, write and writeln attempt to write a value
that is included in the type definition. If the value is not in the type definition,
the compiler terminates program execution and prints an error message.
When you specify a negative field width of a parameter, Pascal truncates all
trailing blanks in the array. write and writeln assume the default values in
Table 6-15 if you do not specify a minimum field length.
Data Type Default Width without -xl Option Default Width with -xl Option
array of char Declared length of the array Declared length of the array
boolean Length of true or false 15
char 1 1
double 21 21
enumerated Length of type 15
hexadecimal 10 10
integer 10 10
integer16 10 10
integer32 10 10
longreal 21 21
octal 10 10
real 21 13
shortreal 13 13
single 13 13
string constant Number of characters in string Number of characters in string
variable-length string Current length of the string Current length of the string
Example
var
x: integer16;
begin
write('Enter an integer: ');
readln(x);
writeln(x: 5, ' is ', x oct, ' in octal.');
writeln(x: 5, ' is ', x hex, ' in hexadecimal.')
end. { octal_example }
xor
The xor function returns the exclusive or of two integer values.
Syntax
xor(int1, int2)
Arguments
int1 and int2 are integer expressions.
Return Value
xor returns an integer value.
Comments
Pascal uses Table 6-16 to return the bitwise exclusive or of int1 and int2.
If int1 and int2 are different size integers, Pascal converts the smaller integer to
the larger integer before it performs the xor operation.
xor is a bitwise operator similar to &, !, and ~. Do not confuse it with the
boolean operators, and, or, and not.
Example
See the example in the land listing on page 142.
This chapter describes the Pascal input and output environments, with
emphasis on interactive programming. It contains the following sections:
203
7
Routine Description
append Opens a file for writing at its end.
close Closes a file.
filesize Returns the current size of a file.
flush Writes the output buffer for the specified Pascal file into the
associated operating system file.
getfile Returns a pointer to the C standard I/O descriptor
associated with the specified Pascal file.
linelimit Terminates program execution after a specified number of
lines has been written into a text file.
message Writes the specified information to stderr.
open Associates an external file with a file variable.
read and readln Read in boolean, integer and floating-point variables,
fixed- and variable-length strings, enumerated types, and
pointers.
remove Removes the specified file.
reset and rewrite Accepts an optional second argument.
seek Resets the current position of a file for random access I/O.
tell Returns the current position of a file.
write and writeln Outputs boolean integer and floating-point variables,
fixed- and variable-length strings, enumerated types, and
pointers; output expressions in octal or hexadecimal; allows
negative field widths.
If the input is from a previously created file, then this reading can take place
without runtime action by you. However, if the input is from a terminal, then
the input is what you type. If the system does an initial read automatically at
the beginning of program execution, and if the input is a terminal, you must
type some input before execution can begin. This makes it impossible for the
program to begin by prompting for input.
Pascal has been designed so that an initial read is not necessary. At any given
time, Pascal may or may not know whether the end-of-file and end-of-line
conditions are true.
Thus, internally, these functions can have three values: true, false, and,
“I don't know yet; if you ask me I'll have to find out.” All files remain in this
last, indeterminate state until the program requires a value for eof or eoln,
either explicitly or implicitly; for example, in a call to read. If you force Pascal
to determine whether the input is at the end of the file or the end of the line, it
must attempt to read from the input.
begin
while not eof do begin
write('Number, please? ');
read(i);
writeln('That was a ', i: 2, '.');
writeln
end
end. { eof_example1 }
At first glance, this may appear to be a correct program for requesting, reading,
and echoing numbers. However, the while loop asks whether eof is true
before the request is printed. Thus, this system is forced to decide whether the
input is at the end of the file. It gives no messages; it simply waits for the user
to type a line, as follows:
Number, please? ^D
standard input: Tried to read past end of file
a.out terminated by signal 5: SIGTRAP
Traceback being written to a.out.trace
Abort (core dumped)
The following code avoids this problem by prompting before testing eof:
begin
write('Number, please? ');
while not eof do begin
read(i);
writeln('That was a ', i: 2, '.');
writeln;
write('Number, please? ')
end
end. { eof_example2 }
You must still type a line before the while test is completed, but the prompt
asks for it. This example, however, is still not correct, because it is first
necessary to know that there is an end-of-line character at the end of each line
in a Pascal text file. Each time you test for the end of the file, eof finds the
end-of-line character. Then, when read attempts to read a character, it skips
past the end-of-line character, and finds the end of the file, which is illegal.
Thus, the modified code still results in the following error message at the end
of a session:
Number, please? ^D
standard input: Tried to read past end of file
Traceback being written to a.out.trace
Abort (core dumped)
The simplest way to correct the problem in this example is to use the procedure
readln instead of read. readln also reads the end-of-line character, and
eof finds the end of the file:
begin
write('Number, please? ');
while not eof do begin
readln(i);
writeln('That was a ', i: 2, '.');
writeln;
write('Number, please? ')
end
end. { eof_example3 }
Number, please? ^D
In general, unless you test the end-of-file condition both before and after calls
to read or readln, there may be input that causes your program to attempt to
read past the end-of-file.
This program almost always has the effect of ignoring the last character in the
line. The read(ch) belongs as part of the normal processing. In Pascal terms,
read(ch) corresponds to ch := input^; get(input).
This code advances the file until the blank corresponding to the end of line is
the current input symbol and then discards this blank. The next character
available from read is the first character of the next line, if one exists.
Permanent Files
Table 7-2 shows how to associate a Pascal file variable with a permanent file.
Association Description
With the open function open associates a permanent file with a file
variable for reading or writing. open can also
determine if a file actually exists.
With the reset and rewrite In Pascal, reset and rewrite take an optional
functions second argument, a file name. If you specify the
file name, the compiler opens the file and associates
it with the given file variable. Any previous file
associated with the file variable is lost.
With the program header If you call reset or rewrite with a file variable
f1, which is bound to a file variable declared f2 in
the program header and do not specify the file
name, Pascal opens a file with the same name as
the variable f2. reset gives a runtime error if the
file does not exist. rewrite creates the file if it
does not exist.
Temporary Files
Table 7-3 shows how to associate a Pascal file variable with a temporary file.
Association Description
With the procedure: file_variable must not be declared in the program
rewrite(file_variable) statement. This procedure creates a temporary file
called #tmp.suffix, where suffix is unique to that
temporary file. When the program exits or leaves the
scope in which file_variable is declared, the file is
deleted.
With the procedure: The procedure creates the temporary file called
rewrite(output) #tmp.suffix, where suffix is unique to that temporary file.
This file is not deleted after program execution.
Now, whenever you direct write or writeln to output, the output is sent to
/home/willow/test. This includes the default case, when you write
without giving a file variable.
If you call rewrite on output and you haven't associated output with an
external file, the program creates a file with a name of the form #tmp.suffix,
where suffix is unique to that file. Pascal does not delete this file after the
program exits.
The data structure also includes the buffer. The buffer normally contains a
single component that is the same type as the type of the file. For example, a
file of char has one character buffer, and a file of integer has one
integer buffer.
For interactive prompting to work, Pascal must print the prompt before
waiting for the response. For this reason, Pascal normally prints all the output
that has been generated for output whenever one of the following conditions
occurs:
• The program calls a writeln.
• The program reads from the terminal.
• The program calls either the message or flush procedure.
In the following code sequence, the output integer does not print until the
writeln occurs:
for i := 1 to 5 do begin
write(i);
Compute a lot with no output
end;
writeln;
Pascal performs line buffering by default. To change the default, you can
compile your program with –b option. When you specify the –b option on the
command-line, the compiler turns on block-buffering with a block size of 1,024.
You can specify this option in a program comment using one of these formats:
{$b0} No buffering.
{$b1} Line buffering. This is the default.
{$b2} Block buffering. The block size is 1,024. Any number greater
than 2, for example, {$b5}, is treated as {$b2}.
This option only has an effect in the main program. The value of the option in
effect at the end statement of the main program is used for the entire program.
Although you can set up a signal handler to trap this signal, you cannot
determine which routine called the signal or the reason it was called.
With Pascal, you can set I/O trap handlers dynamically in your program. The
handler is a user-defined Pascal function.
When an I/O error occurs, Pascal runtime library checks if there is a current
active I/O handler. If one does not exist, Pascal prints an error message,
invokes a SIGTRAP signal, and terminates.
The handler returns a boolean value. If the value is false, the program
terminates. If the value is true, program execution continues with the
statement immediately following the I/O routine that called the trap. The
results of the I/O call remain undefined.
You can set the handler to nil to return it to its default state.
To set an I/O trap handler, you must include the file ioerr.h in your Pascal
source file. ioerr.h consists of an enumeration type of all possible I/O error
values, a type declaration of an io_handler procedure pointer type, and an
external declaration of the set_io_handler routine.
/opt/SUNWspro/SC4.2/include/pascal
type
IOerror_codes = (
IOerr_no_error,
IOerr_eoln_undefined,
IOerr_read_open_for_writing,
IOerr_write_open_for_reading,
IOerr_bad_data_enum_read,
IOerr_bad_data_integer_read,
IOerr_bad_data_real_read,
IOerr_bad_data_string_read,
IOerr_bad_data_varying_read,
IOerr_close_file,
IOerr_close_null_file,
IOerr_open_null_file,
IOerr_create_file,
IOerr_open_file,
IOerr_remove_file,
IOerr_reset_file,
IOerr_seek_file,
IOerr_write_file,
IOerr_file_name_too_long,
IOerr_file_table_overflow,
IOerr_line_limit_exceeded,
IOerr_overflow_integer_read,
IOerr_inactive_file,
IOerr_read_past_eof,
IOerr_non_positive_format
);
var
f: text;
IO_ERROR: IOerror_codes;
str: array [1..10] of char := 'Testing';
begin
if code = IO_ERROR then begin
writeln('ERROR HANDLER ', code);
test_handler := true
end else
test_handler := false
end; { test_handler }
Lexical Elements
Pascal supports the following extensions to the lexical elements of standard
Pascal:
• Uppercase- and lowercase-sensitive
• The special symbols ~, &, |, !, #, and %
• The reserved words external, otherwise, private, public, and univ
• The reserved words define, extern, module, and static
• The identifiers in Table A-1
• An underscore (_) and dollar_sign($) in identifier names
• The comment delimiters /* */. in addition to the standard (* *) and { }
• The comment delimiters " "
219
A
Nonstandard Identifiers
FALSE close index lsr return
TRUE concat integer16 max rshft
addr date integer32 maxchar seed
alfa discard intset message seek
append double land min shortreal
argc exit lastof minchar single
argv expo length minint sizeof
arshft filesize linelimit next stradd
asl firstof lnot null substr
asr flush longreal open tell
assert getfile lor pack trace
bell getenv lshft random trim
card halt lsl remove univ_ptr
clock in_range
Data Types
Pascal supports the following extensions to the standard Pascal data types:
• The real data types shortreal and longreal
• The real data types single and double
• A real constant without a digit after the decimal point
• The integer data types integer16 and integer32
• An integer constant in another base
• Character constants minchar, maxchar, bell, and tab
• Fixed-length and variable-length character strings
• Array initialization using a default upper bound or a repeat count
• A set of type intset, which contains the elements 0 through 127
Statements
Pascal extends the standard definition of statements, as follows:
• The and then and or else operators in the if statement
• The assert statement
• The otherwise statement in a case statement
• Constant ranges in a case statement
• The exit statement in a for, while, or repeat loop
• The next statement in a for, while, or repeat loop
• An identifier as the target of a goto statement
• The return statement in a procedure or function
• An alternative format of the with statement
Built-In Routines
Pascal supports the following nonstandard built-in routines:
• The addr function, which returns the address of a specified variable
• The append procedure, which opens a file for writing at its end
• The argc function, which returns the number of arguments passed to the
program
• The argv procedure, which assigns the specified program argument to a
string variable
• The arshft function, which does an arithmetic right shift of an integer
• The asl function, which does an arithmetic left shift of an integer
Program Compilation
Pascal supports the following extensions to program compilation:
• Sharing variable, procedure, and function declarations across multiple units
using include files
• Sharing variable, procedure, and function declarations across multiple units
using multiple declarations
• Sharing variable, procedure, and function declarations across multiple units
using the extern and define variable declarations
• Sharing variable, procedure, and function declarations between units of
different languages using the extern and external routine options
This Appendix describes the differences between Pascal and Apollo DOMAIN
Pascal, and how the -xl option can be used to get around most of these
differences.
Table B-1 Differences Between Programs Compiled with and without –xl
The default enumerated type size is 16 bits. The default is either 8 or 16 bits, depending on the number
of elements in the enumerated set.
The source file is run through the preprocessor cppas The source file is run through the preprocessor cpp.
before it is processed by the compiler.
227
B
Table B-1 Differences Between Programs Compiled with and without –xl (Continued)
If the value of the expression in a case statement does The compiler generates an error and halts.
not match any of the case values, the program falls
through and does not generate an error. The program
continues execution in the statement immediately
following the case statement.
The writing of enumerated and boolean variables Enumerated variables default to the length of the type.
defaults to uppercase and 15-character width format. boolean variables default to the length of true or false.
Top-level variables, procedures, and functions in Variables, procedures, and functions in programs default to
programs default to private. public.
Modules compiled with –xl are not compatible with These two types of modules are not linked together.
modules compiled without –xl.
Identifiers
Pascal restricts the maximum length of an identifier to 1,024 characters. All
characters are significant.
Data Types
This section describes the restrictions Pascal places on the following data types:
• real
• Integer
• Character
• Record
• Array
• Set
• Alignment
231
C
real
Table C-1 lists the minimum and maximum values Pascal assigns to the real
data types, single and double.
Integer
The value Pascal assigns to the integer constants maxint and minint depends
on whether or not you compile your program with the –xl option, as shown in
Table C-2.
Character
Pascal defines the maximum range of characters as 0 to 255.
Record
Pascal restricts the maximum size of a record to 2,147,483,647 bytes.
Array
Pascal restricts the maximum size of an array to 2,147,483,647 bytes.
Set
Pascal restricts the maximum size of a set to 32,767 elements.
Alignment
The size and alignment of data types depends on whether or not you compile
your program with the –xl option. Table C-3 shows the representation of data
types without –xl, and Table C-4 shows the representation with –xl.
Nested Routines
Pascal allows a maximum of 20 levels of procedure and function nesting.
Data Type Default Width without -xl Option Default Width with -xl Option
array of char Declared length of the array Declared length of the array
boolean Length of true or false 15
char 1 1
double 21 21
enumerated Length of type 15
hexadecimal 10 10
integer 10 10
integer16 10 10
integer32 10 10
longreal 21 21
octal 10 10
real 21 13
shortreal 13 13
single 13 13
string constant Number of characters in the string Number of characters in the string
variable-length string Current length of the string Current length of the string
The Pascal Version 4.2 compiler has been validated using Version 5.5 of the
Pascal Validation Suite. It complies with FIPS PUB 109 ANSI/IEEE 770 X3.97-
1983 and BS6192/ISO7185 at both level 0 and level 1. This appendix is a
summary of the validation.
Test Conditions
The Pascal Version 4.2 compiler was validated under the Solaris 2.5 operating
system on a SPARCstation™ 10 machine.
237
D
Implementation-Defined Features
The implementation-defined features are as follows:
E.2 The subset of real numbers denoted by signed-real are the values
representable in the single precision (32-bit) format of the IEC559:1982
Standard Binary Floating Point Arithmetic for Microprocessor Systems, which
is the same format as in the IEEE standard P754.
E.3 The values of char-type are the ISO 8859/1 (ASCII) character set.
E.4 The ordinal numbers of each value of char-type are the corresponding
ISO 8859/1 (ASCII) code value.
E.5 All file operations are performed at the point where they are encountered
at execution time, with the exception of get (both explicit and where
implied by reset and read), which is delayed in its execution to the
point at which the file is next referenced—a technique known as “lazy
I/O.”
E.13 The case in the output of the value of boolean-type is uppercase for the
initial letter, and lowercase for the remaining letters.
E.16 The effects of reset and rewrite on the standard files input and
output depend on the binding of these files specified at the invocation
of the program. In general, reset and rewrite have the effects
described in clause 6.6.5.2 of the Pascal Standard1 when input and output
have been bound to permanent files. When the binding is to a device,
reset(input) has no effect other than discarding any partially
processed line. rewrite(output) terminates any partially complete
line but has no other effect. rewrite(input) and reset(output) are
treated as errors.
Reporting of Errors
The following errors are detected prior to, or during, execution of a program:
D.1, D.3, D.7, D.9, D.10, D.11, D.14, D.15, D.16, D.17, D.18, D.23, D.26, D.29,
D.33, D.34, D.35, D.36, D.37, D.40, D.41, D.42, D.45, D.46, D.47, D.49, D.51,
D.52, D.53, D.54, D.55, D.56, D.57, D.58, D.59
D.2, D.4, D.5, D.6, D.8, D.12, D.13, D.19, D.20, D.21, D.22, D.24, D.25, D.27,
D.28, D.30, D.31, D.32, D.38, D.39, D.43, D.44, D.48, D.50
1. The American National Standard Pascal Computer Programming Language, ANSI/IEE 770 X3.97-1983,
published by the Institute of Electrical and Electronics Engineers, Inc., 345 East 47th Street, New York,
NY 10017, c. 1983.
Implementation-Dependent Features
Implementation-dependent features F.1 to F.11 of Pascal are treated as
undetected errors.
Extensions
The processor does not contain any extensions to BS6192/ISO 7185. Such
extensions must be enabled by means of a compiling option, not the subject of
validation.
This glossary defines some general programming terms, as well as terms that
are specific to Pascal.
|
The bitwise or operator.
~
The bitwise not operator.
!
The bitwise or operator.
#
A programming symbol that specifies an integer value in a base other than 10,
includes a file in your program, or indicates a preprocessor command.
%
A programming symbol used with the –xl option for special cppas directives.
&
The bitwise and operator.
adb
An interactive, general-purpose, assembly-level debugger.
addr
A built-in function that returns the address of a specified variable.
241
alfa
An array of char 10 characters long.
and then
An operator similar to the standard and operator. The difference is that
and then enforces left-to-right evaluation and evaluates the right operand
only if the left operand is true.
append
A built-in procedure that opens a file for writing at its end.
argc
A built-in function that returns the number of arguments passed to the
program.
argv
A built-in procedure that assigns the specified program argument to a string
variable.
arshft
A built-in function that does an arithmetic right shift of an integer value.
asl
A built-in function that does an arithmetic left shift of an integer value.
asr
A built-in function that does an arithmetic right shift of an integer value. Same
as arshft.
assert
A statement which causes a boolean expression to be evaluated and aborts
the program if false, provided that the –C option is specified.
bell
A predeclared character constant equal to char(7), which makes the terminal
beep.
block buffering
Output buffering with a block size of 1,024.
card
A built-in function that returns the number of elements of a set variable.
clock
A built-in function that returns the user time consumed by the process.
compiler directive
A percent sign (%) followed by a name indicating an action for the cppas
preprocessor to take. Programs that contain compiler directives must be
compiled with the –xl option.
concat
A built-in function that concatenates two strings.
conditional variable
A variable, either defined or undefined, handled by the cppas preprocessor. A
conditional variable is defined when it appears in a %var directive. Programs
that contain conditional variables must be compiled with the –xl option.
%config
A compiler directive that is a special predefined conditional variable with a
value of either true or false. Programs that contain the %config directive
must be compiled with the –xl option.
cppas
The preprocessor that handles the Pascal conditional variables and compiler
directives when the -xl option is specified.
date
A built-in procedure that fetches the current date (as assigned when the
operating system was initialized) and assigns it to a string variable.
dbx
A symbolic debugger that understands Pascal, Modula-2, C, and FORTRAN
programs.
%debug
A compiler directive that works with the -cond compiler option.
-cond instructs pc, the Pascal compiler, to compile the lines in your program
that begin with %debug. Programs that contain the %debug directive must be
compiled with the –xl option.
define attribute
An attribute used to declare a variable that is allocated in the current module
and whose scope is public.
Glossary 243
define declaration
A declaration used to declare a variable that is allocated in the current module
and whose scope is public.
discard
A built-in procedure that throws away the value a function returns.
double
A real data type that represents a 64-bit floating-point number. Same as
longreal.
%else
A compiler directive that provides an alternative action to the %if directive. If
the expression in %if is false, the compiler skips over the %then part and
executes the %else part instead. Programs that contain the %else directive
must be compiled with the –xl option.
%elseif
A compiler directive that provides another alternative action to the %if
directive. If the expression in %if is false, the compiler skips over the %then
part and executes the %elseif part instead. Programs that contain the
%elseif directive must be compiled with the –xl option.
%elseifdef
A compiler directive that provides an alternative action to the %ifdef
directive. If the expression in %ifdef is false, the compiler skips over the
%then part and executes the %elseifdef part instead. Programs that contain
the %elseifdef directive must be compiled with the –xl option.
%enable
A compiler directive that sets a conditional variable to true. Programs that
contain the %enable directive must be compiled with the –xl option.
%endif
A compiler directive that indicates the end of the %if or %ifdef directive.
Programs that contain the %endif directive must be compiled with the –xl
option.
%error
A compiler directive that prints a string on the standard output and treats it as
an error. Programs that contain the %error directive must be compiled with
the –xl option.
exit
A statement used in a for, while, or repeat loop to transfer program control
to the first statement after the loop.
%exit
A compiler directive that causes the compiler to stop processing the current
Pascal source file. Programs that contain the %exit directive must be
compiled with the –xl option.
expo
A built-in function that calculates the integer-valued exponent of a specified
number.
extern attribute
An attribute used to declare a variable that is not allocated in the current
program or module unit, but is a reference to a variable allocated in another
unit.
extern option
A procedure and function option that indicates the procedure or function is
defined in a separate program or module unit, and possibly in a different
source language. Same as external.
external
A procedure and function option that indicates the procedure or function is
defined in a separate program or module unit, and possibly in a different
source language. Same as extern.
filesize
A built-in function that returns the current size of a file.
firstof
A built-in function that returns the first possible value of a type or variable.
flush
A built-in procedure that writes the output buffered for the specified Pascal file
into the associated operating system file.
Glossary 245
getenv
A built-in function that returns the value associated with an environment
name.
getfile
A built-in function that returns a pointer to the C standard I/O descriptor
associated with a Pascal file.
halt
A built-in procedure that terminates program execution.
%if
A compiler directive. When the compiler encounters a %if expression %then
directive, it evaluates expression. If expression is true, the compiler executes
the statements after %then. If expression is false, the compiler skips over
%then. Programs that contain the %if directive must be compiled with the –
xl option.
%ifdef
A compiler directive that determines whether or not a conditional variable in a
%var directive has been previously defined. Programs that contain the
%ifdef directive must be compiled with the –xl option.
I/O handler
A Pascal function that is passed the values err_code and filep when an I/O
error occurs. The handler returns false to terminate the program, or true to
continue program execution.
in
A parameter type indicating the parameter can only pass a value into a
procedure or function.
in out
A parameter type indicating the parameter can both take in values and pass
them back out.
in_range
A built-in function that checks if a value is in a defined subrange.
%include
A compiler directive that instructs cppas to insert the lines from the specified
file in the input stream. Programs that contain the %include directive must
be compiled with the –xl option.
index
A built-in function that returns the position of the first occurrence of a string or
character in another string.
input
A special predefined file variable equivalent to the standard input file, stdin.
integer16
An integer data type that represents a 16-bit value.
integer32
An integer data type that represents a 32-bit value.
internal
A procedure and function option that makes the procedure or function local to
a module.
intset
A predefined set of [0..127].
land
A built-in function that returns the bitwise and of two integers.
lastof
A built-in function that returns the last possible value of a type or variable.
length
A built-in function that returns the length of a string.
line buffering
The buffering of output line-by-line.
linelimit
A built-in procedure that terminates execution of a program after a specified
number of lines have been written into a text file.
%list
A compiler directive that enables a listing of the program. Programs that
contain the %list directive must be compiled with the –xl option.
Glossary 247
lnot
A built-in function that returns the bitwise not of an integer value.
longreal
A real data type that represents a 64-bit floating-point number. Same as
double.
lor
A built-in function that returns the inclusive or of two integer values.
lshft
A built-in function that does a logical left shift of an integer value.
lsl
A built-in function that does a logical left shift of an integer value. Same as
lshft.
lsr
A built-in function that does a logical right shift of an integer value. Same as
rshft.
max
A built-in function that evaluates two scalar expression and returns the larger
one.
maxchar
A predeclared character constant equal to char(255).
maxint
An integer constant that represents the 16-bit value 32,767 when you compile
your program with the –xl option; otherwise, maxint represents the 32-bit
value 2,147,483,647.
message
A built-in procedure that writes the specified information on stderr, usually
the terminal.
min
A built-in function that evaluates two scalar expressions and returns the
smaller one.
minchar
A predeclared character constant equal to char(0).
module heading
A heading that contains the reserved word module followed by an identifier.
For example, module sum; is a legal module heading.
module unit
A source program that does not have a program header.
next
A statement used in a for, while, or repeat loop to skip to the next iteration
of the current loop.
%nolist
A compiler directive that disables the program listing. Programs that contain
the %nolist directive must be compiled with the –xl option.
nonpascal
A procedure and function option that declares non-Pascal routines when you
are porting Apollo DOMAIN programs written in DOMAIN Pascal,
FORTRAN, C, and C++.
null
A built-in procedure that performs no operation.
open
A built-in procedure that associates an external file with a file variable.
or else
An operator similar to the standard or operator. The difference is that
or else enforces left-to-right evaluation and evaluates the right operand only
if the left operand is false.
otherwise
A Pascal extension to the standard Pascal case statement. If the value of the
case selector is not in the case label list, Pascal executes the statements in the
otherwise clause.
out
A parameter indicating that the parameter is used to pass values out of the
routine.
Glossary 249
output
A special predefined file variable equivalent to the standard output file,
stdout.
private
A variable, procedure, or function declaration that restricts its accessibility to
the current compilation unit.
procedure and
function pointer
A pointer that has the address of a procedure or function as its value.
public
A variable, procedure, or function declaration that is visible across multiple
programs and modules.
random
A built-in function that generates a random number between 0.0 and 1.0.
remove
A built-in procedure that removes the specified file.
return
A statement used in a procedure or function to prematurely end the procedure
or function.
rshft
A built-in function that does a logical right shift of an integer value.
seed
A built-in function that reseeds the random number generator.
seek
A built-in procedure that resets the current position of a file.
shortreal
A real data type that represents a 32-bit floating point number. Same as
single.
single
A real data type that represents a 32-bit floating point number. Same as
shortreal.
%slibrary
A compiler directive that directs cppas to insert the lines from the specified
file in the input stream. Same as %include. Programs that contain the
%slibrary directive must be compiled with the –xl option.
stradd
A built-in procedure that adds a string to the end of another string.
static
A variable attribute that declares the variable private in scope.
stderr
The standard operating system error file.
stdin
The standard operating system input file.
stdout
The standard operating system output file.
stlimit
A built-in procedure that terminates program execution if a specified number
of statements have been executed in the current loop.
string
An array of char 80 characters long.
substr
A built-in function that extracts a substring from a string.
sysclock
A built-in function that returns the system time consumed by the process.
tab
A predeclared character constant equal to char(9), which makes a tab
character.
tell
A built-in function that returns the current position of a file.
Glossary 251
time
A built-in procedure that retrieves the current time.
trace
A built-in procedure that prints stack traceback.
trim
A built-in function that removes trailing blanks in a character string.
unit
Either a program or a module.
univ
A modifier used before data types in formal parameter lists to turn off type
checking for that parameter.
univ_ptr
See universal pointer.
universal pointer
A pointer used to compare a pointer of one type to another or to assign a
pointer of one type to another.
%var
A compiler directive that defines conditional variables for the preprocessor.
Programs that contain the %var directive must be compiled with the –xl
option.
variable attribute
An attribute that determines how to allocate the variable. Variable attributes
include static, extern, and define.
variable initialization
The initialization of a real, integer, boolean, character, set, record, array, or
pointer variable in the var declaration of the program.
variable-length string
A string of variable length. A variable-length string can be assigned a string of
any length, up to the maximum length specified in the declaration. Pascal
ignores any characters specified over the maximum.
varying
A string of variable length.
wallclock
A built-in function that returns the elapsed number of seconds since
00.00.00 GMT January 1, 1970.
%warning
A compiler directive that tells the compiler to print a string on the standard
output as a warning. Programs that contain the %warning directive must be
compiled with the –xl option.
–xl option
An option of the pc command that causes the compiler to implement Pascal as
DOMAIN Pascal.
xor
A built-in function that returns the exclusive or of two integers.
Glossary 253
254 Pascal Language Reference
Index
A varying, 34
addr function, 99, 222 arrays, 73
alfa data type, 34 arshft function, 97, 107, 171, 222
alignment of data types, 233 ASCII character set, 1
and operator, 2, 221 asl function, 97, 109, 222
and then operator, 69 to 70 asr function, 97, 111, 171, 223
AnswerBook, xxiii assert statement, 48, 221
Apollo DOMAIN Pascal, 227 to 229 assignment statement, 13, 18, 20, 22
append function, 102, 222 assignments, 63 to 65
compatibility rules, 64
argc
data types, 63
function, 99, 105, 222
extensions, 221
procedure, 105
null strings, 65
argv procedure, 99, 105, 222 string constants, 65
arithmetic strings, to and from, 64
left shift, 109
operators, 66
right shift, 108 B
routines, 95 –b option to pc command, 214
array data types, 34 to 37 bell character, 23, 220
alfa, 34 bit operators, 66
as function return value, 89 bitwise operators, 151
conformant, 89 and, 2, 221
data representation, 37 not, 201, 221
declaring variables, 34 or, 2, 201, 221
initializing variables, 36
block buffering, 214
string, 34
boolean
univ parameter type, 89
expression, 48
255
operators, 66 conventions, typographical, xxii
and then, 69 to 70
or else, 71
D
boolean data types, 20 to 21
assignment compatibility rules, 63 data structure, 213
declaring constants, 21 data types
declaring variables, 20 alignment, 233
initializing variables, 20 array, 34 to 37
buffering assignments, 63
block, 214 boolean, 20 to 22
file output, 213 enumerated, 24
line, 214 extensions, 220
file, 41
built-in procedures and functions, 2
integer, 232
nonstandard, 95 to 201, 203, 222
internal representation
standard, 95, 203
with –xl, 235
without –xl, 234
C pointer, 41 to 45, 80
–C option to pc command, 48, 218 real, 231
real, 13 to 15
C programming language, 94, 204
record, 27 to 33
card function, 96, 112, 223
set, 38 to 39
case statement, 48, 51 to 52, 157, 221 size restrictions, 232
otherwise clause, 51, 58 space allocation, 232
range of constants, 52 subrange, 25
with –xl option, 51
date procedure, 99, 118, 223
character
declarations, 77 to 84
data type, 23
const, 79, 222
assignment compatibility
define, 222
rules, 63
extensions, 221
bell, 23, 220
label, 222
data representation, 23
type, 222
declaring constants, 23
var, 14, 18, 27, 80 to 83
declaring variables, 22
default field widths, 236
maxchar, 23, 220
minchar, 23, 220 define
tab, 23, 220 declaration, 83, 222
set, 1 variable, 80, 222
string routines, 97 discard procedure, 99, 120, 223
clock function, 99, 113, 223 documentation, xxiii to xxiv
close procedure, 98, 116, 204, 223 DOMAIN Pascal, 227 to 229
comments, 6, 48, 214, 219 features accepted but ignored, 227,
228
concat function, 117, 223
features not supported, 229
conformant array, 89
–xl option, 227
const declaration, 77, 79, 222
Index 257
getfile, 98, 134, 204, 215 H
in_range, 138
halt procedure, 99, 136, 223
index, 97, 139
internal option, 92 headings
land, 97, 142 extensions, 221
lastof, 144 function, 84
length, 97, 145 program, 210
lnot, 97, 149
lor, 97, 150 I
lshft, 97, 152
identifiers, 2, 4, 54, 59
lsl, 97, 153
as labels, 77
lsr, 97, 153
in define declaration, 83
max, 96, 153
nonstandard predeclared, 4, 220
min, 96, 156
restrictions to, 231
nonpascal option, 94
standard predeclared, 4, 220
parameters, 85 to 88
private, 84, 92, 222 if statement, 48, 208, 221
public, 84, 222 implementation restrictions, 231 to 236
random, 96, 162 in out parameter, 85, 88
return statement, 59 to 60 in parameter, 85, 88, 215
return value, 89, 121 in_range function, 138, 223
returning structured types, 222 include directive and statement, 216
rshft, 97, 171
index function, 97, 139, 223
seed, 96, 172
sizeof, 96, 176 initializing variables, 83
substr, 97, 183 input
sysclock, 99, 114, 184 environment, 203 to 218
tell, 224 error recovery, 214
time, 185 extensions, 225
trim, 97, 191, 225 file
type transfer, 99, 193 stdin, 212
var declaration, 14, 18, 21, 23, 28 variable, 211
variable option, 92 input and output
wallclock, 99, 195 library, 212
xor, 97, 200 routines, nonstandard and
standard, 204
trap handler, 215
G integer data types, 16 to 20
getenv function, 99, 132, 223 assignment compatibility rules, 63
getfile function, 98, 134, 204, 215, 223 data representation, 19
global variable, 81 declaring constants, 18
goto statement, 48, 54, 59, 221 integer, 17
exiting current block, 54 integer16, 17, 220
use of identifier in, 54 integer32, 220
maxint, 232
minint, 19, 232
Index 259
nonpascal, 94, 227 assignment compatibility rules, 63
variable, 92 data representation, 45
or else operator, 70 declaring variables, 42
or operator, 2, 201, 221 initializing variables, 45
procedure and function, 43, 80
otherwise clause in case statement, 51,
univ_ptr, 42
58
universal, 80
out parameter, 85, 88
precedence of operators, 76
output
private
environment, 203 to 218
function, 84
error recovery, 214
procedure, 84
extensions, 225
variable, 81, 222
file
buffering, 213 procedure
stdout, 212 append, 222
variable, 211 argc, 105
argv, 99, 105
association with define
P declaration, 84
packed records, 30 built-in, 95
parameters, 84 to 89 close, 98, 116, 204
formal, 86, 88, 92 date, 99, 118
in, 85, 88, 215 declarations, 77
in out, 85, 88 discard, 99, 120
out, 85, 88 extensions, 222
passing conventions, 86 extern option, 92
type checking, 88 external option, 92
univ type, 88 flush, 98, 130, 204, 213
value, 86 forward option, 92
var, 86, 88 halt, 99, 136
Pascal internal option, 92
extensions in the compiler, xix linelimit, 98, 147, 204
symbols, 2 message, 98, 155, 204, 213
validation summary, 237 to 240 nonpascal option, 94
null, 99, 157
pc command
open, 98, 117, 158, 204, 210
–b option, 214
parameters, 85 to 89
–C option, 48, 218
pcexit, 99
document reference, 2
private, 92, 222
–L option, 2, 228
public, 222
–s option, 2, 3
read, 23, 98, 163, 204, 205, 207, 209,
–V0 option, 3
211
–V1 option, 3
readln, 23, 98, 135, 163, 204, 207, 209,
–xl option, 9, 17, 24, 94, 227, 234
211
pcexit procedure, 99 remove, 98, 166, 204
pointer data type, 41 to 45 reset, 98, 117, 135, 167, 204, 212
Index 261
halt, 99, 136, 223 var declaration, 36, 39
in_range, 96, 138, 223 variable option, 92
index, 97, 139, 140, 223 wallclock, 99, 195, 225
input and output, 203 write, 98, 155, 198, 204, 211, 212, 225
internal option, 92 writeln, 98, 155, 198, 204, 211, 212,
land, 97, 142, 223 225
lastof, 96, 144, 223 xor, 97, 200, 225
length, 97, 146, 223 routine parameters, 85 to 89
linelimit, 98, 147, 204, 223 routines, 79
lnot, 97, 149, 223 rshft function, 97, 171, 224
lor, 97, 150, 224
lshft, 97, 152, 224
lsl, 97, 153 S
lsr, 97, 153, 224 –s option to pc command, 2, 3
max, 96, 224 scope of variables
message, 98, 155, 204, 213, 224 private, 80
min, 96, 157, 224 public, 80
nonpascal option, 94
seed function, 162, 172, 224
null, 99, 157, 224
open, 98, 117, 158, 204, 210, 224 seek procedure, 174, 224
parameters, 85 to 89 set
private, 84, 92 data types, 38 to 39
public, 84 as function return value, 91
random, 96, 162, 224 assignment compatibility
read, 98, 163, 204, 205, 207, 209, 211, rules, 63
224 data representation, 39
readln, 98, 135, 163, 204, 207, 209, declaring variables, 38
211, 224 returning number of
remove, 98, 166, 204, 224 elements, 112
reset, 98, 117, 135, 167, 204, 212, 224 initializing variables, 83
return statement, 59 operators, 66, 71
rewrite, 98, 117, 135, 169, 204, 211, shortreal, 13, 15, 220
225 signal handler, 214
rshft, 97, 171, 224 single, 13, 15, 220, 232
seed, 96, 172, 224 sizeof function, 176, 224
seek, 98
space allocation of data types, 233
sizeof, 96, 176, 224
stlimit, 99, 180, 224 special symbols, nonstandard and
stradd, 97 standard, 2
substr, 97, 183, 224 standard files
sysclock, 99, 114, 184, 224 error, 212
tell, 98, 185, 224 input, 212
time, 99, 187, 224 output, 212
trace, 99, 189, 225 statements, 47 to 62
trim, 97, 191, 225 assert, 48, 221
type transfer, 99, 193, 225 case, 47, 51 to 52, 157, 221
Index 263
write procedure, 23, 98, 155, 198, 204,
211, 212, 225
writeln procedure, 23, 98, 155, 198, 204,
211, 212, 225
X
–xl option to pc command, 9, 17, 24, 227
with define attribute, 83
with nonpascal routine option, 94
xor function, 97, 200, 225