Previous Next Contents Index Doc Set Home


Built-In Procedures and Functions

6


This chapter describes the built-in procedures and functions Pascal supports. It starts with two major sections:

Standard Procedures and Functions

page 95

Routines Specific to Pascal (Summary)

page 96

Routines Specific to Pascal (Details)

page 99

The third section, beginning on page 99, lists the nonstandard routines alphabetically and contains detailed descriptions and examples of each routine.


Standard Procedures and Functions

Pascal supplies the standard procedures listed in Table 6-1, and the standard functions listed in Table 6-2.

Table  6-1 Standard Procedures

dispose

page

readln

unpack

get

put

reset

write

new

read

rewrite

writeln

pack

Table  6-2 Standard Functions

abs

eof

odd

round

sqrt

arctan

eoln

ord

sin

succ

chr

exp

pred

sqr

trunc

cos

ln


Routines Specific to Pascal (Summary)

This section lists the nonstandard Pascal procedures and functions according to the following categories:

Table 6-3 through Table 6-8 summarize these Pascal routines.

Table  6-3 Nonstandard Arithmetic Routines

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.


Table  6-4 Nonstandard Bit Shift Routines

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.


Table  6-5 Nonstandard Character String Routines

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.


Table  6-6 Nonstandard Input and Output Routines

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.

Table  6-7 Extensions to Standard Input and Output Routines

Routine
Description

read and readln

Reads in boolean variables, fixed- and variable-length strings, and enumerated types from the standard input.

reset and rewrite

Accepts an optional second argument, an operating system file name.

write and writeln

Outputs enumerated type values to the standard output.

Outputs expressions in octal or hexadecimal.

Allows negative field widths.


Table  6-8 Miscellaneous Nonstandard Routines

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.


Routines Specific to Pascal (Details)

Described in this section are the detailed descriptions for each of the Pascal-specific routines: its syntax, arguments, and return value. Comments and an example are also included.

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.

addr cannot be applied to bit-aligned fields of aggregates.


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

The Pascal program, addr.p

program addr_example(output);

{ This program demonstrates the use of the 
  addr function. }

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;

    { Get the address of x. }
    ptr_address := addr(x);

    { Get the contents of ptr_address. }
    y := ptr_address^;
    writeln('The address of x is  ', ptr_address: 3, '.');
    writeln('The contents of x is ', y: 3, '.');

    { Get the address of the constant name. }
    ptr_address_char := addr(name);

    { Get the contents of ptr_address_char. }
    c := ptr_address_char^;

    writeln('The address of c is  ', ptr_address_char: 3, '.');
    writeln('The contents of c is ', c: 4, '.')
end. { addr_example }

The commands to compile and execute addr.p

hostname% pc addr.p
hostname% a.out
The address of x is 38764.
The contents of x is 2147483647.
The address of c is 33060.
The contents of c is Gail.

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.

filename, which is optional, is a string of fixed or variable length, or a string constant.

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');
If you do not pass an optional second argument, Pascal creates a new temporary file, which is deleted when the program is terminated.

See also the sections: "reset," "rewrite," and "close."

Example

The example that follows shows how to use append.

The Pascal program, files.p

program files_example(input, output);
const
  MaxLength = 80;
var
  f: text;
  line: varying [MaxLength] of char;
begin
  rewrite(f, 'poem.txt');
  writeln('Enter a lines of text and hit Control+D to end the 
job.');
  while not eof do begin
    readln(line);
    writeln(f, line);
  end;
  close(f);
  writeln;
  writeln('There 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);
  
  reset(input); { Because Control+D close input }
  append(f, 'poem.txt');
  writeln('Append a lines of text and hit Control+D to end the 
job.');
  while not eof do begin
    readln(line);
    writeln(f, line);
  end;
  close(f);
  writeln;
  writeln('There are the lines of all text you input:');
  reset(f, 'poem.txt');
  while not eof(f) do begin
    readln(f, line);
    writeln(line);
  end;
  close(f);
end.

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.

a is a fixed- or variable-length string.

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

The Pascal program, argv.p

program argv_example(output);

{ This program demonstrates the use of
  argc and argv. }

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 }

The commands to output and execute argv.p

hostname% pc argv.p
hostname% a.out
The name of the program is a.out.
hostname% a.out one two three
The name of the program is a.out.
Argument number 1 is one.
Argument number 2 is two.
Argument number 3 is three.

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
If you shift this number to the right by 1:

(arshft (-8, 1) )
your result is:

1111 1111 1111 1100
The result arshft returns is machine-dependent, and is unspecified unless the following is true:

0 <= sh <= 32

Example

The Pascal program, arshft.p

program arshft_example(input, output);

{ This program demonstrates the arithmetic right shift. }

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 }

The commands to compile and execute arshft.p. The value the bit-shift routines return may depend upon the architecture of your system.

hostname% pc arshft.p
hostname% a.out
Enter a positive or negative integer: -2
Arithmetic right shift 1 bit(s): FFFFFFFF
Arithmetic right shift 2 bit(s): FFFFFFFF
Arithmetic right shift 3 bit(s): FFFFFFFF
Arithmetic right shift 4 bit(s): FFFFFFFF
Arithmetic right shift 5 bit(s): FFFFFFFF
Arithmetic right shift 6 bit(s): FFFFFFFF
Arithmetic right shift 7 bit(s): FFFFFFFF
Arithmetic right shift 8 bit(s): FFFFFFFF

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.

The result asl returns is machine-dependent and is unspecified unless the following is true:

0 <= sh <= 32

Example

The Pascal program, asl.p

program asl_example(input, output);

{ This program demonstrates the arithmetic left shift. }

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 }

The commands to compile and execute asl.p

hostname% pc asl.p
hostname% a.out
Enter a positive or negative integer: 19
Arithmetic left shift 1 bit(s): 26
Arithmetic left shift 2 bit(s): 4C
Arithmetic left shift 3 bit(s): 98
Arithmetic left shift 4 bit(s): 130
Arithmetic left shift 5 bit(s): 260
Arithmetic left shift 6 bit(s): 4C0
Arithmetic left shift 7 bit(s): 980
Arithmetic left shift 8 bit(s): 1300

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

The Pascal program, card.p

program card_example(output);

{ This program demonstrates the use of the card function. }
type
    lowints = 0..100;
    primary_colors = set of (red, yellow, blue);
    possibilities = set of boolean;
    capital_letters = set of 'A'..'Z';
    digits = set of lowints;

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 }

The commands to output and execute card.p

hostname% pc card.p
hostname% a.out
There are     3 primary colors.
There are     2 possibilities.
There are    26 capital letters.
There are   101 digits.

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

The Pascal program, clock.p

program clock_example(input, output);

{ This program times how long it takes to run the
  towers of hanoi. }

const
    DISK = 16;

var
    num: array [1..3] of integer;
    counts: integer32;
    before_user: integer;
    before_sys: integer;
    after_user: integer;
    after_sys: integer;

procedure moves(number, f, t: 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 }

clock.p Program (Screen 1 of 2)

begin { main program }
    before_user := clock;
    before_sys := sysclock;
    moves(DISK, 1, 3);
    after_sys := sysclock;
    after_user := clock;
    write('For ', DISK: 1, ' disks, there were ');
    writeln(counts: 1, ' steps.');
    write('Elapsed system time:  ');
    writeln(after_sys - before_sys: 1, ' milliseconds.');
    write('Elapsed user time:  ');
    writeln(after_user - before_user: 1, ' milliseconds.')
end. { clock_example }

clock.p Program (Screen 2 of 2)

 

The commands to compile and execute clock.p. The time clock and sysclock return is system-dependent.

hostname% a.out
For 16 disks, there were 65535 steps.
Elapsed system time: 16 milliseconds.
Elapsed user time: 583 milliseconds.

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.

str2 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.

See also the section: "stradd."

Example

The Pascal program, concat.p

program concat_example(output);
var 
  color: varying [10] of char := ' Black';
  
begin
  writeln(concat(color, 'bird' + '.'));
end.

The commands to compile and execute concat.p

hostname% pc concat.p
hostname% a.out
 Blackbird.

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.

Use the environment variable LC_TIME to set the necessary locale.

See also the section: "time."

Example

The Pascal program, date.p

program date_example(output);

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.

The commands to compile and execute date.p

hostname% pc date.p
hostname% a.out
The date is 12/19/94.
The date is 12/19/94.
The date is 12/19/94.
The date is 12/19/94.
hostname% setenv LC_TIME ru
hostname% a.out
The date is 19.12.94.
The date is 19.12.94.
The date is 19.12.94.
The date is 19.12.94.
hostname% setenv LC_TIME C
hostname% a.out
The date is 12/19/94.
The date is 12/19/94.
The date is 12/19/94.
The date is 12/19/94.

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

The Pascal program, discard.p

program discard_example(output);

{ This program computes a discount if the total amount 
  is over DISC_AMOUNT. }

const
    RATE = 0.15;
    DISC_AMOUNT = 100.00;

var
    amount: single;
    discount: single;

function compute(amount: single): single;

begin
    compute := amount * RATE
end; { compute }

begin { main program }
    write('Enter sale amount:  ');
    readln(amount);
    if amount < DISC_AMOUNT then begin
      discard(compute(amount));
      write('No discount applied; total charge amount');
	writeln(' must be more than ', DISC_AMOUNT: 2: 2, '.')
    end else begin
      discount := compute(amount);
      write('The amount of discount on ');
      writeln(amount: 2: 2, ' is ', discount: 2: 2, '.')
    end
end. { discard_example }

The commands to compile and execute discard.p

hostname% pc discard.p 
hostname% a.out 
Enter sale amount: 125.00
The amount of discount on 125.00 is 18.75.

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

The Pascal program, expo.p

program expo_example(output);

{ This program demonstrates the expo function. }

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 }

The value expo returns may depend upon the architecture of your system.

hostname% pc expo.p
hostname% a.out
 x  r := exp(x)					expo(r)
 -  -----------		-------
 1  2.71828182845905e+00 					    0
 2  7.38905609893065e+00 					    0
 3  2.00855369231877e+01 					    1
 4  5.45981500331442e+01					     1
 5  1.48413159102577e+02					     2
 6  4.03428793492735e+02					     2
 7  1.09663315842846e+03					     3
 8  2.98095798704173e+03					     3
 9  8.10308392757538e+03					     3
10  2.20264657948067e+04					     4

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.

For a binary file of type file of T, filesize returns the number of elements of type T in the file.

See also the sections, "seek," and "tell."

Example

The Pascal program, filesize.p

program filesize_example;
var
  ft: text;
  fi: file of integer;
  i:  integer;
begin
  rewrite(ft);
  rewrite(fi);
  i := 10;
  write(ft, i, i);
  write(fi, i, i);
  writeln('size of a text of an integer =', filesize(ft):
3, ' bytes');
  writeln('size of a file of an integer =', filesize(fi):
3, ' elements');
  close(ft);
  close(fi)
end. { filesize_example }

The commands to compile and execute filesize.p

hostname% pc filesize.p
hostname% a.out
size of a text of an integer = 20 bytes
size of a file of an integer =  2 elements

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.

When x is ...
The value firstof returns ...

An ordinal type, a constant, an expression, or variable

Has the same data type as its argument.

An array

Has the same data type as the type of the array index.

A set type

Has the same data type as the base type of the set.

Comments

Pascal follows the rules in Table 6-9 when returning the value of x.




Table  6-9 firstof Return Values

Type of Argument
Return Value

integer (without -xl option)

-2,147,483,648

integer (with -xl option)

-32,768

integer16

-32,768

integer32

-2,147,483,648

char

chr(0)

boolean

false

Enumerated

The first element in the enumeration type declaration.

array

The lower bound of the subrange that defines the
array size.

varying

1

set of 'A'..'Z'

A (the character A).

Example

See the examples that follow.

The Pascal program, firstof.p

program firstof_example(output);

{  This program illustrates the use of firstof and lastof
   used with arrays and enumerated types. }

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;

    for i := firstof(continents) to lastof(continents) do begin
        writeln(i, ' is the goal of ', planned_targets[i]: 1,
' dollars per tourist.')
    end

end. { firstof_example }

The commands to compile and execute firstof.p

hostname% pc firstof.p
hostname% a.out
North_America is the goal of 2000 dollars per tourist.
South_America is the goal of 300 dollars per tourist.
Asia is the goal of 1500 dollars per tourist.
Europe is the goal of 2500 dollars per tourist.
Africa is the goal of 500 dollars per tourist.
Australia is the goal of 100 dollars per tourist.
Antarctica is the goal of 0 dollars per tourist.

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

The Pascal program, flush.p

program flush_example(output);

{ This program demonstrates the use of the
  flush procedure. }

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)

begin { main program }
    rewrite(f1, NAME);
    for i := 1 to 10 do 
      write(f1, i);

    { At this point the file is still empty. }
    read_file;

    flush(f1);

    { Now the file contains data after the flush. }
    read_file
end. { flush_example }

flush.p (Screen 2 of 2)

The commands to compile and execute flush.p

hostname% pc flush.p
hostname% a.out
Beginning of file.
End of file.

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.

See the Solaris documentation for a complete description of environment variables.

Example

The Pascal program, getenv.p

program getenv_example;

{ This program demonstrates the use of the
  getenv function. }

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 }

The commands to compile and execute getenv.p

hostname% pc getenv.p
hostname% a.out
EDITOR = /usr/ucb/vi
EDITOR = /usr/ucb/vi

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

The Pascal program, getfile.p

program getfile_example;

{ This program demonstrates the use of the getfile function. }

type
    char_array = array [1..30] of char;

var
    f: text;
    cfile: univ_ptr;

procedure fprintf(cf: univ_ptr; in format: char_array;
                  in year: integer); external c;

begin { main program }
    rewrite(f, 'output.data');
    cfile := getfile(f);
    fprintf(cfile, 'Hello, world, in the year %d .', 1996)
end. { getfile_example }

The commands to compile and execute getfile.p

hostname% pc getfile.p
hostname% a.out
hostname% more output.data
Hello, world, in the year 1996 .

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:

Call to procedure halt
Pascal returns to command level after it executes halt.

Example

The Pascal program, halt.p

program halt_example(input, output);

{ This program calculates a factorial. }

var
    x, y: integer;

function factorial(n: integer): integer;

begin
    if n = 0 then 
      factorial := 1
    else 
      factorial := n * factorial(n - 1)
end; { factorial } { factorial }

begin { main program }
    write('Enter a positive integer from 0 to 16:  ');
    readln(x);
    if (x >= 0) and (x <= 16) then begin
      y := factorial(x);
      write('The factorial of ', x: 1);
      writeln(' is ', y: 1, '.')
    end else begin
      writeln('Illegal input.');
      halt
    end
end. { halt_example }

The commands to compile and execute halt.p

hostname% pc halt.p
hostname% a.out
Enter a positive integer from 0 to 16: 8
The factorial of 8 is 40320.
hostname% a.out
Enter a positive integer from 0 to 16: 20
Illegal input.
Call to procedure halt

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

The Pascal program, in_range.p

program in_range_example(input, output);

{ This program demonstrates the use of the in_range function. }

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 }

The commands to compile and execute in_range.p

hostname% pc in_range.p
hostname% a.out
Enter values for triangle base and height: 4 5
Area is 10.00.

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.

pattern_string is a constant string, variable-length string, an array of character, or a 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.

If the pattern_string is not found in the target_string, index returns 0. If pattern_string is the null string, index returns -1.

Example

See the example that follows.

The Pascal program, index.p

program index_example;

{ This program demonstrates the use of
  the index function. }

const
    MAX = 20;
    STRING = 'FOO';

type
    char_array = varying [MAX] of char;

var
    s1: char_array := 'INDEX_EXAMPLE';
    s2: char_array := 'EXAMPLE';
    i: integer16;

procedure print(index: integer; s1: char_array;
                s2: char_array);

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 }

begin { main program }
    i := index(s1, s2);
    print(i, s1, s2);
    i := index(s1, STRING);
    print(i, s1, STRING)
end. { index_example }

The commands to compile and execute index.p

hostname% pc index.p
hostname% a.out
The string EXAMPLE is at index 7 in the string INDEX_EXAMPLE.
The string FOO is not in the string INDEX_EXAMPLE.

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.




Table  6-10 land Truth

Value of Bit in int1
Value of Bit in int2

Value of Bit in result

0

0

0

0

1

0

1

0

0

1

1

1

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

The Pascal program, land.p

program land_example;

{  This program demonstrates the use of the land, lor,
   lor, and xor functions. }

procedure BinaryOutput(intval: integer32);

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 }

 

The commands to compile and execute land.p. The value the bit-shift routines return may depend upon the architecture of your system.

hostname% pc land.p
hostname% a.out
IVAL1 
 Decimal : 15 Binary : 00000000000000000000000000001111
IVAL2 
 Decimal : 255 Binary :00000000000000000000000011111111
LNOT(IVAL1)
 Decimal : -16 Binary :11111111111111111111111111110000
LAND(IVAL1,IVAL2)
 Decimal : 15 Binary : 00000000000000000000000000001111
LOR(IVAL1,IVAL2)
 Decimal : 255 Binary :00000000000000000000000011111111
XOR(IVAL1,IVAL2)
 Decimal : 240 Binary :00000000000000000000000011110000

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.

When x is a set type, the value lastof returns has the same data type as the base type of the set.

Comments

Pascal follows the rules in Table 6-11 when returning the value of x.




Table  6-11 lastof Return Values

Type of Argument
Return Value

integer (without -xl)

2,147,483,647

integer (with -xl)

32,767

integer16

32,767

integer32

2,147,483,647

char

chr(255)

boolean

true

enumerated

The last element in the enumeration type declaration.

array

The upper bound of the subrange that defines the array size.

varying

The upper bound of the varying string.

set of 'A'..'Z'

The character Z.

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

The Pascal program, length.p

program length_example(output);

{ This program demonstrates the use of the length function. }

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 }

The commands to compile and execute length.p

hostname% pc length.p
hostname% a.out
The length of string one is 15.
The length of string two is 10.
The combined length is 25.

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.

n is a positive integer expression.

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

The Pascal program, linelimit.p

program linelimit_example;

{ This program demonstrates the use of the
  linelimit procedure. }

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 }

The commands to compile and execute linelimit.p

hostname% pc -C linelimit.p
hostname% a.out
Enter the names of your children.
The last entry should be "0".
Ryan
Matthew
Jennifer
Lynne
Lisa
Ann
Katherine
Devon
Geoffrey
Bria

linelimit.dat : Line limit exceeded
*** a.out terminated by signal 5: SIGTRAP
*** Traceback being written to a.out.trace
Abort (core dumped)

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.

Table  6-12 lnot Truth

Value of Bit in int
Value of Bit in result

0

1

1

0

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.




Table  6-13 lor Truth

Value of Bit in intl1

Value of Bit in int2

Value of Bit in result

0

0

0

0

1

1

1

0

1

1

1

1

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.

The Pascal program, lshft.p

program lshft_example(input, output);

{ This program does a logical left shift. }

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 }

The commands to compile and execute lshft.p. The value the bit-shift routines return may depend upon the architecture of your system.

hostname% pc lshft.p
hostname% a.out
Enter a positive or negative integer: 3
Logical left shift 1 bit(s):   6
Logical left shift 2 bit(s):   C
Logical left shift 3 bit(s):  18
Logical left shift 4 bit(s):  30
Logical left shift 5 bit(s):  60
Logical left shift 6 bit(s):  C0
Logical left shift 7 bit(s): 180
Logical left shift 8 bit(s): 300

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.

See also the min listing on page 156.

Example

The Pascal program, max.p

program max_example(input, output);

{ This program reads in 10 positive integers
  in the range 1 through 501 and determines
  the largest even and smallest odd.Out of range numbers
  are rejected. }

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 }

The commands to compile and execute max.p

hostname% pc max.p
hostname% a.out
Please enter 10 integers between 0 and 501:
56 431 23 88 222 67 131 337 401 99
The smallest odd number is 23.
The largest even number is 222.

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.

message(x1, ..., xN) is equivalent to the following code:

writeln(errout, x1, ..., xN);
flush(errout);
flush(output);
    .
    .
 { Flush all open files. }

Example

The Pascal program, message.p

program message_example(output);

{ This program demonstrates the use of the
  message function. }

begin
    writeln('This message will go to standard output.');
    message('This message will go to standard error.')
end. { message_example }

The commands to compile and execute message.p

hostname% pc message.p
hostname% a.out > temp_file
This message will go to standard error.
hostname% cat temp_file
This message will go to standard output.
hostname% a.out >& temp_file
hostname% cat temp_file
This message will go to standard output.
This message will go to standard error.

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:

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.

pathname must be one of the following:

history instructs the compiler whether to create the file or what to do with it if it exists. history must be one of these values:

'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.




Table  6-14 open Error Codes

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.

The Pascal program, open.p

program open_example;

{ This program demonstrates the use of the open procedure. }

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);

    { Open a file specified by a command line argument. }
    open(infile, '^1', 'unknown', error);
    if error = 0 then begin
      argv(1, name);
      writeln('Opened ', name, ' for reading.');
      close(infile)
    end else 
      writeln('No command line argument; error code =', error);

    { Open a file that may or may not exist. }
    { Prompt user for name of file at runtime. }
    open(infile, file3, 'unknown', error);
    if error = 0 then begin
      writeln('Opened file for reading.');
      close(infile)
    end else 
      writeln('Error opening file', error)
end. { open_example }

The commands to compile and execute open.p

hostname% pc open.p
hostname% a.out
Opened open1.txt for reading.
No command line argument; error code =     1
Enter_a_filename-- test.txt
Opened file for reading.

pcexit

The pcexit 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

The Pascal program, random.p

program random_example(output);

{ This program demonstrates the use of
  the random function. }

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 }

The commands to compile and execute random.p

hostname% pc random.p
hostname% a.out
These numbers were generated at random:
    97    6    48    91    35

read and readln

Pascal supports the standard form of read and readln with three extensions:

Syntax

read(file, var1 ..., varN);

readln(file, var1 ..., varN);

Arguments

file is an optional variable having either the text or file data type.

var can be any real, integer, character, boolean, subrange, enumerated, or array variable or a fixed- or variable-length string variable. If read or readln is used in a function to define the function result, var can also be an identifier of that function.

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.

With both variable- and fixed-length strings, if the number of characters on a line is more than the maximum length of the string, the next read picks up where the last read left off. With readln, the rest of the line is discarded, so the next read or readln begins at the next line.

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:

Unknown name "value" found on enumerated type read
Trace/BPT trap (core dumped)
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, ...)
is treated as if it were an assignment of the form:

f:=e
where e is the input value. This feature is an extension of the Pascal Standard, and so cannot be used with the -s option.

Example

The Pascal program, read.p

program read_example(input, output);

{ This program uses readln to input strings,
  boolean data, and enumerated data. }

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 }

The commands to compile and execute read.p

hostname% pc read.p
hostname% a.out
Enter type of gem: diamond 
Enter cut: marquis, emerald, round, pear_shaped: pear_shaped
Enter true if this a gift, false if it is not: true
You have selected a diamond with a pear_shaped cut.
We will gift wrap your purchase for you.

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

The Pascal program, remove.p

program remove_example;

{ This program demonstrates the use of the
  remove procedure. }

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 }

The commands to compile and execute remove.p

hostname% pc remove.p 
hostname% touch rmc 
hostname% ls rmc 
rmc 
hostname% a.out rmc 
hostname% ls rmc 
rmc not found

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.

filename is a fixed- or variable-length string, or a string constant.

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.

filename is a fixed- or variable-length string, or a string constant.

Return Value

rewrite does not return any values.

Comments

rewrite gives you permission to modify a file.

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 you do not give an optional second argument, Pascal creates a physical operating system file for you. This file has the same name as the file variable if the file variable is listed in the program header. If the file variable is not listed in the program header, Pascal creates a temporary file with the name #tmp.suffix. The temporary file is deleted when the program terminates.

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

The Pascal program, rewrite.p

program rewrite_example(input, output);

{ This program demonstrates the use of rewrite 
  and reset.}

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 }

The commands to compile and execute rewrite.p

hostname% pc rewrite.p
hostname%  a.out
Enter a line of text. Hit Control-D to end the job.
Hello, how are you?
Please keep in touch
 ^D

These are the lines of text you input:
Hello, how are you?
Please keep in touch.

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.

The Pascal program, rshft.p

program rshft_example(input, output);

{ This program demonstrates the logical right shift. }

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 }

The commands to compile and execute rshft.p. The value the bit-shift routines return may depend upon the architecture of your system.

hostname% pc rshft.p
hostname% a.out
Enter a positive or negative integer: 32
Logical right shift 1 bit(s):					     10
Logical right shift 2 bit(s):					      8
Logical right shift 3 bit(s):					      4
Logical right shift 4 bit(s):					      2
Logical right shift 5 bit(s):					      1
Logical right shift 6 bit(s):					      0
Logical right shift 7 bit(s):					      0
Logical right shift 8 bit(s):					      0

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.

The Pascal program, seed.p

program seed_example(output);

{ This program demonstrates the use of the
  seed function. }

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 }

The commands to compile and execute seed.p

hostname% pc seed.p 
hostname% a.out 
These numbers were generated at random:
   75   175   186   260   178

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.

pos is a positive integer.

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:

seek(file, 0) or seek(file, tell(file))

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.

See also the sections: "filesize," and "tell."

Example

The Pascal program, seek.p

program seek_example;
var
  f: file of integer;
  i: integer;
begin
  rewrite(f);
  for i:= 0 to 9 do
    write(f, i);
  writeln('Initial size of f =', filesize(f) :3, ' elements');
  reset(f);
  seek(f, 4);
  read(f, i);
  writeln('The 4th element of f =', i :3);
  rewrite(f);
  write(f, i);
  seek(f, 100);
  write(f, i);
  writeln('Final size of f =', filesize(f):3, ' elements');
  close(f);
end. { seek_example }

The commands to compile and execute seek.p

hostname% pc seek.p
hostname% a.out
Initial size of f = 10 elements
The 4th element of f =  4
Final size of f =101 elements

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.

tag is a constant. This argument is optional.

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
However, if S is defined as follows:

var S: varying [12] of char;
begin
    S:='';

then sizeof (S) = 16. Moreover,

sizeof (''+'') = 4
because the '+' string operator returns a varying string object.

Example

The Pascal program, sizeof.p

program sizeof_example(output);

{ This program demonstrates the use of the
  sizeof function. }

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;

sizeof.p Program (Screen 1 of 2)

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 }

sizeof.p Program (Screen 2 of 2)

The commands to compile and execute sizeof.p. The value sizeof returns may depend upon the architecture of your system.

hostname% pc sizeof.p
hostname% a.out
The size of boolean is	1.
The size of char is	1.
The size of color1 is	1.
The size of color2 is	1.
The size of file is	2089.
The size of integer is 	4.
The size of integer16 is 	2.
The size of integer32 is 	4.
The size of longreal is 	8.
The size of shortreal is 	4.
The size of real is 	8.
The size of rec_type is 	32.
The size of rec_type.ar is	20.
The size of subB is	1.
The size of sub1 (8) is	1.
The size of sub2 (128) is	1.
The size of sub3 (256) is	2.
The size of univ_ptr is	4.

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:

Statement count limit of x exceeded
Trace/BPT trap (core dumped)
If stlimit is used without a loop, it reports the number of statements executed and the CPU time utilized.

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

The Pascal program, stlimit.p

 program stlimit_example;
{$p+}

{ This program demonstrates the use 
  of the stlimit procedure. }

begin
    repeat
      writeln('Hello.');
      stlimit(10)
    until false
end. { stlimit_example }

The commands to compile and execute stlimit.p

hostname% pc stlimit.p
hostname% a.out
Hello.
Hello.
Hello.
Hello.

Statement count limit of 11 exceeded
Trace/BPT trap (core dumped)

stradd

The stradd procedure adds a string to another string.

Syntax

stradd(strdest, strsrc)

Arguments

strdest is a variable-length string.

strsrc is a variable-length string, a character array, or a character-string constant.

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.

stradd avoids allocating temporary storage. An example is the assignment str1 := str1 + str2, in which the compiler copies str1 into some temporary storage, appends str2, and copies the result back into str1.

If the resulting string is longer than the maximum length of strdest, it is truncated to this maximum length.

See also the section: "concat."

Example

The Pascal program, stradd.p

program stradd_example(output);
var 
  greeting: varying [20] of char := ' Hello';
  
begin
  stradd(greeting, ',');
  stradd(greeting, ' world');
  stradd(greeting, '!');
  writeln(greeting);
end.

The commands to compile and execute stradd.p

hostname% pc stradd.p
hostname% a.out
 Hello, world!

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.

n is a positive integer or zero.

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

The Pascal program, substr.p

program substr_example(output);

{ This program demonstrates the use of the
  substr function. }

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 }

The commands to compile and execute substr.p

hostname% pc substr.p
hostname% a.out
Paris, France

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.

See also the sections on: "filesize," "seek."

Example

The Pascal program, tell.p

program tell_example;
var
  ft: text;
  fi: file of integer;
  i: integer;
begin
  rewrite(ft);
  rewrite(fi);
  for i:= 1 to 3 do begin
    writeln('tell(ft) =', tell(ft) :3);
    writeln('tell(fi) =', tell(fi) :3);
    writeln(ft, i :3);
    write(fi, i);
  end;
  close(ft);
  close(fi)
end. { tell_example }

The commands to compile and execute tell.p

hostname% pc tell.p
hostname% a.out
tell(ft) =  0
tell(fi) =  0
tell(ft) =  4
tell(fi) =  1
tell(ft) =  8
tell(fi) =  2

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.

Use the environment variable LC_TIME to set the necessary locale.

See also the section: "date."

Example

The Pascal program, time.p

program time_example(output);

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.

The commands to compile and execute time.p

hostname% pc time.p
hostname% a.out
The time is 14:02:49.
The time is 14:02:49.
The time is 14:02:49.
The time is 14:02:49.
hostname% setenv LC_TIME ru
hostname% a.out
The time is 14:02:56.
The time is 14:02:56.
The time is 14:02:56.
The time is 14:02:56.
hostname% setenv LC_TIME C
hostname% a.out
The time is 14:03:21.
The time is 14:03:21.
The time is 14:03:21.
The time is 14:03:21.

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

The Pascal program, trace.p

program trace_example;

procedure subr(count: integer);
begin
  if (count > 0 ) then
    subr(count - 1)
  else
    trace;
end;

begin
  subr(5);
end.

The commands to compile and execute trace.p

hostname% pc trace.p -g
hostname% a.out
hostname% cat a.out.trace

### Stacktrace of a.out
  [4] subr(count = 0), line 8 in "trace.p"
  [5] subr(count = 1), line 6 in "trace.p"
  [6] subr(count = 2), line 6 in "trace.p"
  [7] subr(count = 3), line 6 in "trace.p"
  [8] subr(count = 4), line 6 in "trace.p"
  [9] subr(count = 5), line 6 in "trace.p"
  [10] program(), line 12 in "trace.p"
detaching from process 28226

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

The Pascal program, trim.p

program trim_example;

{ This program demonstrates the use of the trim function. }
const
    TEN = '          ';
    MAX = 10;
type
    large = varying [100] of char;
    s_type = array [1..MAX] of char;
    v_type = varying [MAX] of char;
var
    c1: char := ' ';
    st1: s_type := '123456    ';
    st2: s_type := '          ';
    st3: s_type := '0123456789';
    v1: v_type := '01234     ';
    v2: v_type := '          ';
    v3: v_type := '0123456789';
    l: large;

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 }

The commands to compile and execute trim.p

hostname% pc trim.p
hostname% a.out
1234560123456789         16
34560         5
0123401234567891234560123456789         31

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.

x is a variable, constant, or expression.

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;

To transfer the value of variable x to a floating-point number, you would write:

y := single(x);

When the argument of a type transfer function is a variable, the size of the argument must be the same as the size of the destination type. However, if the argument to a transfer function is a constant or an expression, Pascal attempts to convert the argument to the destination type because constants and expressions do not have explicit types.

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

The Pascal program, type.p

program type_transfer_example(output);

{ This program uses transfer functions to 
  convert integer to character. }

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 }

The commands to compile and execute type.p

hostname% pc type.p
hostname% a.out
The character value of 65 is A.
The character value of 66 is B.
The character value of 67 is C.
The character value of 68 is D.
The character value of 69 is E.
The character value of 70 is F.
The character value of 71 is G.
The character value of 72 is H.
The character value of 73 is I.
The character value of 74 is J.
The character value of 75 is K.
The character value of 76 is L.
The character value of 77 is M.
The character value of 78 is N.
The character value of 79 is O.
The character value of 80 is P.
The character value of 81 is Q.
The character value of 82 is R.
The character value of 83 is S.
The character value of 84 is T.
The character value of 85 is U.
The character value of 86 is V.
The character value of 87 is W.
The character value of 88 is X.
The character value of 89 is Y.
The character value of 90 is Z.

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.

The Pascal program, wallclock.p

program wallclock_example(output);

{ This program demonstrates the use of the 
  wallclock function. }

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;

{ Compute fibonacci number recursively. }
function fib(number: integer): integer;

begin
    if number > 2 then 
      fib := fib(number - 1) + fib(number - 2)
    else 
      fib := 1
end; { fib }

begin { main program }
    writeln('Begin computing fibonacci series.');
    write(NTIMES, ' Iterations:  ');
    start := wallclock;
    for i := 1 to NTIMES do 
      value := fib(NUMBER);
    finish := wallclock;
    writeln('Fibonacci(', NUMBER: 2, ') = ', value: 4, '.');
    writeln('Elapsed time is ', finish - start: 3, ' seconds.')
end. { wallclock_example }

The commands to compile and execute wallclock.p

hostname% pc wallclock.p
hostname% a.out
Begin computing fibonacci series.
    20 Iterations: Fibonacci(24) = 46368.
Elapsed time is   5 seconds.

write and writeln

Pascal supports the standard form of write and writeln with the following extensions:

Syntax

write(file, exp1:width ..., expN:width)

writeln(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.

exp is a variable, constant, or expression of type integer, real, character, boolean, enumerated, or string. exp cannot be a set variable.

width is an integer. width is optional.

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.

To write the internal representation of an expression in octal, use this form:

write(x oct);
x is a boolean, character, integer, pointer, or user-defined type. It can also be a constant, expression, or variable.

To write an expression in hexadecimal, use this form:

write(x hex);
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.




Table  6-15 Default Field Widths

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

The Pascal program, octal.p

program octal_example(output);

{ This program writes a number in octal
  and hexadecimal format. }

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 }

The commands to compile and execute octal.p

hostname% pc octal.p
hostname% a.out
Enter an integer: 10
 10 is       12 in octal.
 10 is       A in hexadecimal.

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.

Table  6-16 xor Truth

Value of Bit in int1
Value of Bit in int2

Value of Bit in result

0

0

0

0

1

1

1

0

1

1

1

1

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.


Previous Next Contents Index Doc Set Home