130
CBASIC® lANGUAGE REFERENCE MANUAL

DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

Embed Size (px)

Citation preview

Page 1: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC®lANGUAGE

REFERENCEMANUAL

Page 2: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

J

I

I

VC BAS I C

A commercially-oriented,compiler/interpreter BASIC

language facility forCP/M (tm) systems.

Version 2

November 1981

Digital Research, Inc.P. O. Box 579

Pacific Grove, CA 93950

408-649-3896

All Rights Reserved

Page 3: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

Copyright (c) 1977,1978 by Digital Research Inc.All rights reserved.

No part of this publication may be reproduced,transmitted, transcribed, stored in a retrievalsystem, or translated into any language orcomputer language, in any form or by any means,electronic, mechanical, magnetic, optical,chemical, manual or otherwise, without the priorwritten permission of Digital Research Inc., PostOffice Box 579, Pacific Grove, California, 93950.

DISCLAIMER

Digital Research makes no representations orwarranties with respect to the contents hereof andspecifically disclaims any implied warranties ormerchantability or fitness for any particularpurpose. Further, Digital Research reserves theright to revise this publica"tion and to makechanges from time to time in the content hereofwithout obligation of Digital Research to notifyany person of such revision or changes.

TRADEMARKS

CBASIC and MP/M are trademarks of Digital ResearchCP/~1 is a registered trademark of Digital Research

"J

Page 4: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

TABLE OF CONTENTS

Introduction . • • . . . • . . • • . . . • 1For CBASIC I Programmers . .••..•. 2An Explanation of Identification Numbers . • • . 3

Strings. . . . . . .. . 10Numbers. . . . . . . . • . •. .••..•. 10Identifiers. .• . ..•.•.•...••• 12VariabllO!s and Subscripted Variables. • . • . . • 12Expressions. . • . • . . . •• ••. •• 15AssignrnlO!nt Statements. . • • • • • . • . . . • . 17

1.

1.11.21.3

2.

2.12.22.32.42.5

3.

3.13.23.33.43.53.6

4.

INTRODUCTION • .

GENERAL INFORMATION..

Statements • . •. .• . •Notation • . • • . • . .Statement Numbers. . .•.••REM Sta-tement. • •. • • •Executing a CBASIC Program

FORMING EXPRESSIONS ••

CONTROL STNrEMENTS •

1

4

45567

· 10

· 19

· . . . . 19· . . . . 19

• •• • 20• 20

· . . . . 22• 22• 23· 25· 25· 26• 27• 27• 28

GOSUB Statement.. . •••RETURN Statement . • • • . • . • .GOTO Statement . ..• • . • . •IF ••. THEN .•• ELSE Statement.WHILE S1:atement. • • • • . • •WEND Statement . • • • . . • . • . •FOR Statement. • . • • . • .•NEXT Statement • • • . . . . . . • • • . • • .ON ••• GOSUB, ON ..• GOTO Statements ••••.•.STOP Statement . • • . • • .RANDOMI~m Statement. • •• ....•• • •CHAIN S1:atement. • • • • • • • • •• •.•COMMON Statement . • . . • • • . • •

4.14.24.34.44.54.64.74.84.94.104.114.124.13

III

Page 5: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

5. INPUT/OUTPUT STATEMENTS AND FUNCTIONS. · . 31

5.1 General Information. · · · · · · · · · · · · 315.2 PRINT Statement. · · · · · 31 'oJ5.3 LPRINTER Statement · · · · · · · · · · 325.4 CONSOLE Statement. · · · · · · · · · · · 335.5 POS Predefined Function. · · 345.6 TAB Predefined Function. · · · · · · · · 345.7 READ Statement · · · · · · · · · · · 355.8 DATA Statement · · · · · · · · 355.9 RESTORE Statement. · · · · · · · · · 365.10 INPU1' Statement. · · · · · · · · · · · · · 365.11 OUT Statement. . · · · · · · · · · 385.12 INP Predefined Function. · · · · · · · · 395.13 CONSTAT% Predefined Function · · · · · 395.14 CONCHAR% Predefined Function · · · · · · 39

6. MACHINE LANGUAGE LINKAGE STATEMENTS AND FUNCTIONS.. 41

6.16.26.36.46.5

PEEK Predefined Function .POKE Statement .. ••...•.CALL Statement . • . . . . . .SAVEMEM Statement.. . .•.Use of Integers .•.•.

· . . . . . 41· . . . . . 41

· • . . . 42· .. . 42

· . 43

7. PRED:EFINED FUNCTIONS · 45

7.17.27.3

Numeric Functions .•String Functions .Disk Functions . . .

· . • • • • . . • • 45• • •• ••••• 49

• • • • • • • • • • • • 56

8. USER DEFINED FUNCTIONS · 59

8.18.28.3

Function Names . . . . . • •Function Definition.....•.Function Reference • . • .

· . . . 59· . . . . . . . 60

· 62

9. FORMJ\TTED PRINTING · . . . . . . 63

9.1 General.... . 639.2 String Character Field .••.•.•. 649.3 Fixed Length String Fields. • •...•.. 649.4 Variable Length String Fields. .. ...•. 649.5 Numer ic Data Fields. . • •. .... 659.6 :Escape Characters. . . • . . . • • • • . 68

10. FILES . • · 69

10.110.210.3

How CP/M Maintains Files •.OPEN Statement. . • . . . . • • .CLOSE Statement . . • • . . • . .

IV

· . . . . 69· . . . . . . 69

71

Page 6: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

HL4 CREAT]~ Statement. . . . · · · · 72HL5 DELETl~ Statement. · · · · · · 72HL6 IF END Statement. . . . · · · · 73

V HL7 FILE Statement. . . . · · · · · 74HL8 READ Statement. . · · · · · · · 75HL9 PRINT Statement . · · . . · · · · · 7710.10 Appending to a File · · · · · · 7910.11 Re-Initializing the Disk System · · · · 80

· 91

• 82

· • • . 95

· 91· . 91

· . . . 92· . . . 93• . . . 93

· • 95· . . . 95

· • 97· • . . 98

· 98

· . . . . 82· . . 82

· 83· 83· 86· 86· 88

· . . . . 89

System Requirements • • . • . • .CBASIC Compile-Time Toggles •compiler OutputTRACE • . • • .Cross Reference Lister •.

Directive Format. . . . . . . ..Listing Control Directives•.....•%INCLUDE. • . . . . • . . . • . . . . .%CHAIN. • • • • . • • • • • . • •END Statement . • . . . . •

File Facilities •. .•.•••.File Organization . . • • .Stream Organization . . . • • . . . . • .Fixed Organization . .. .•....File j~ccessing Methods. . . • . . . .Sequential Access . ••• . . .Random Access • • . . . • • . .Speci~l Features. . ••.

OPERATIONAL CONSIDERATIONS.

COMPILER DIRECTIVES . .

PROGRAMMING WITH FILES.11.

11.111.211.311.411.511.611.711.8

12.

12.112.212.312.412.5

( 13.V

13.113.213.313.413.5

APPENDICES

A. COMPILER ERlROR MESSAGES . 101

B. RUNTIME ERROR MESSAGES .. 107

C. KEY WORDS 113

D. DECIMAL - ASCII - HEX TABLE • • 114

E. MASTER INDEX 115

v

Page 7: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

'-.J

Page 8: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

1. CBASIC

1.1 Introduction

Introduction

CP/MMP/M.alsothe

This manual describes version two of CBASIC, acomprehensive, commercially oriented compiler/interpreterdesigned for use with the CP/M (tm) and MP/M-801 (tm)operating systems. CP/M and MP/M-801 are trademarks ofDigital Research. CP/M is available on a multitude of801801, 80185, and Z801 microcomputer systems.

In this manual, unless it is stated otherwise,will be used to indicate version 1 or 2 of CP/M orThere are many derivations of CP/M. CBASIC shouldoperate with these systems. CPU will refer tomicroprocessor chip installed in the system.

CBASIC has a variety of 'extended features includingthe IF ••• 'I~HEN .•• ELSE and WHILE constructs and access todisk files. CBASIC also allO'lN's the use of 3l-charactervariable names, and the free use of cpmments, spaces, andtabs. These aid in creating programs that areself-documenting and maintainable.

Version two of CBASIC adds integer variables, multipleline funct:ions, chaining with common variables, andadditional pre-defined functions as well as otherimprovement:s. A cross-reference lister is also provided.

The CBJ!~SIC system consists of three programs. Thefirst pro<.:Jram, the compiler, converts the user's sourcelanguage program into a series of coded operations thatare placed on an intermediate disk file. The secondprogram, the runtime monitor, directly executes theoperations included in the intermediate file. The finalprogram, XREF.COM, will produce a cross reference listingof all variables used in a CBASIC source program.

1

Page 9: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Introduction

To use CBASIC a microcomputer system using the CP/Moperating system must be available. This manual assumesa working knowledge of the following CP/M documentation:

(a) AN INTRODUCTION TO CP/M FEATURES AND FACILITIES(b) ED: A CONTEXT EDITOR FOR THE CP/M DISK SYSTEM(c) CP/M INTERFACE GUIDE

These manuals are available from Digital Research, PO Box579, Pacific Grove, California.

A newcomer to the field of computers would do well toread an introductory text on the Basic Language.

The reference section, chapters 2 through 10,describes the facilities of the language. Chapter 11expands on the use of files. Chapters 12 and 13 describeoperation of the compiler. Three appendices follow whichlist compiler and runtime error messages and list keywords.

1.2 For CBASIC I Programmers

Programmers familiar with version 1 of CBASIC shouldreview this manual paying particular attention to the useof integer variables. Chapter 3 provides details on usingintegers in expressions. The sections concerning newstatements and functions should be read in detail.Chapters 12 and 13 also contain much new information.

A program that compiled and executed with version 1should operate properly with version 2. However, an INTfile created by the version 1 compiler will not executewith the version 2 runtime monitor. The source programmust be recompiled.

If statements appear not to operate properly, DigitalResearch Inc. would appreciate a note which includes thestatement or statements which are causing the problemalong with a description of the problem.

2

Page 10: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Introduction

"V1.3 Program Identification Numbers

All Digital Research language programs sign-on withthe program name followed by an identification number.These numbers are in the following form:

V.RC

·'V.. is the version number. This manual describes version2 programs. The "R" is the release number of the program.As errbrs are corrected in a particular version, newreleases are made available. The "C" is theconfiguration. A zero means that the program isconfigured to operate with standard CP/M with the TPA at100H. Configuration three has been modified to supportthe large files provided by CP/M version 2 andMP/M. Other configurations m.ay be made available in thefuture.

3

Page 11: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

2. GENERAL INFORMATION

General Information

2.1 Statements

A program consists of zero or more properly formedCBASIC statements contained in a diskette file. CBASICsource statements are also called source code or sourcestatements. An END statement, if present, terminates theprogram, and any statements following the END statementare ignored. An end-of-file on the source file alsoterminates the program. In this case the END statement issupplied by CBASIC.

In this manual the term line, in the context of aline of source code, means a string of charactersterminated with a carriage return and line feed. Astatement may span more than one line or multiplestateme~nts may appear on the same line.

The~ entire ASCII character set is accepted, but moststateme~nts may be written using the common 64 charactersubset. Lower case letters are converted by the compilerto upper case except when they appear in strings orremarksl. A compiler toggle, described in Chapter 13, willinhibit all conversion to upper case.

CBASIC statements are free-form with the followingrequirE!ments:

(1.) When a statement is not completed on a singleline, a continuation character (\) must be used.(Note that with configuration 1 an at sign (@) mayalso be used as the continuation character). Thes1:atement can then be continued on the next line.CBASIC keywords, variable names and string constantsmay not be broken in the middle and continued on thenext line. A continuation character may not be usedin a Data Statement since it is treated as acharacter within a string constant. Likewisebacks lash characters within string constantsinclosed in quotation marks (see section 3.1) are nottreated as continuation characters.

...J

(:2) Allcharactercompiler.

characters which followon the same line are

4

the continuationignored by the

Page 12: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC version 2 General Information

,I

V

(3) MUltiple statements are allowed on one line but'they must be separated by a colon ( : ) . DATA, DEF,~IM, and END must be the only statement on a line; anlF stat.ement must be the first statement on a line.See the REM statement (section 2.4) for an exceptionto this rule.

S9aces may precede statements; any number of spacesmay appear wherever one space is permitted. Extra spaces,such as for indenting statements to enhance readability,do not increase the size of the intermediate file createdby the compiler.

2.2 Notation

All of the CBASIC statements are described in thismanual. Each description includes a synopsis whichpresents the general form of the statement. The followingnotation is used for the synopsis:

Keywords and SymbolsAll spE~cial characters and capitalized wordsrepresent symbols which have special meaning in thelanguage. For instance READ, REM and PRINT arekeywords in CBASIC. Appendix C contains a list ofall ke~l1Ords used by CBASIC.

Angle Brackets < >Angle brackets enclose an item which is defined ingreater detail in the text.

Brackets [ ]Brackets denote an optional feature.

Braces { }Braces indicate that the enclosed section may berepeated zero or more times.

2.3 Statement Numbers

S"batement: numbers are optional. They are ignoredexcep"b when they appear in a GOTO, GOSUB, ON, or IFstatement. In these cases, the statement number mustappea:rr as t:he label of one and only one statement in theprogram. St:atement numbers do not have to be insequential order. For example:

4" INPUT ITEMBRINT I'l?EM3" GOTC> 4"

5

Page 13: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 General Information

statement numbersformat. This is aprocedures that will beit helps to insure that

In this program the line number 30 is not required: it isignor,ed during compilation. However, the 40 appears in aGOTO statement and thus must be used as a statement number "~

once and only once in the program. Statement numbers maycontain any number of digits but only the first 31 areconsidered significant by the compiler.

An additional feature of CBASIC statement numbering isthat any valid number may be used as a statement number.This allows the use of non-integer statement numbers. Itis possible to write an entire program or subprogram withstatement numbers that are all decimal fractions andrange between two consecutive integers.

can even be in exponential (E)convenient feature when writingincluded in other programs becausestatement numbers will be unique.

The following are examples of valid CBASIC statementnumbers:

1o100100.0100.213l00E2l

../The statement numbers 100 and 100.0 are treated as

different statement numbers by the compiler. In otherwords it is the string of characters which determines thestatement number and not the numeric value.

2.4 REM Statement

[<stint nl,Unber>] llEM «$t.t:'~n9 termini:lted with CR>]

[ <stInt nl,Unper>] R~m< [<st.ring terminated with CR>]

A REM statement is ignored by the compiler, andcompilation continues with the statement following thenext carriage return. A continuation character causes thenext line to be part of the remark. The REM statement maybe used to document a program. REM statements do notaffect the size of the program that may be compiled orexecuted. An unlabeled REM statement may follow anystatement on the same line. The statement number of aremark may be used in a GOTO, GOSUB, IF, or ON statement.

6

Page 14: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

Examples of REM statements follow:

General Information

REM THIS IS A REMARKremark This is also a remarktax = 0.15 * income rem lowest tax rate REM \

this section contains the \tax tables for Calif()rnia

The final example shows a REM statement on the same linewith another statement. When using the REM statement inthis manner, a colon is optional between the twostatements. In all other cases involving mUltiplestatements on the same line, the colon must separate thestatements. In addition, if the REM statement is used onthe same line with other statements, it must be the laststatement on the line.

2.5 Executing a CBASIC Program

Execution of a CBASIC program consists of threesteps. First the source program must be created on disk.Next the program is compiled by executing the CBASICcompiler with the name of the source program provided as afile name. Finally the intermediate (INT) file created bythe compiler is executed by invoking the runtime program,again using the source program name as a file name.

The source program will normally be created using atext editor. The source program must have a file type ofBAS. Each line of a source program is terminated by acarriage return and line feed. The line may be anylength, however, the compiler listing will only print thefirst 132 characters of each line.

When typing source programs, identifiers (variablenames, reserved words, and user-defined function names)may not be, abbreviated and must be separated by acharacter olther than a number or letter. In general,spaces will be used to delimit identifiers. All lettersin identifiers are converted to uppercase unless theconversion is inhibited by compiler toggle D (see Chapter13) .

7

Page 15: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 General Information

CBASIC differs from many other basics in itsrequirement that keywords and identifiers may not be runtogether. For instance:

READA

is not accepted by the CBASIC compiler.must be written:

READ A

The statement

FORI=JT010 is a valid CBASIC statement, but itassigns the variable JT010 to the variable FORI.

The CBASIC compiler is invoked as follows:

CBAS2 <filename> [<disk ref>] [$<toggle> {<toggle>}]

where filename is the name of the source file. A filetype of BAS is assumed by the compiler. Compiler toggles,preceded by a dollar sign, may follow the file name. Theyare discussed in Chapter 13.

The compiler produces an intermediate file in theCBASIC machine language. The intermediate file uses thesame name as the source program but of type INT. The INTfile is normally placed on the same disk as the sourcefile. The disk reference is used to specify the drive onwhich the programmer desires to have the INT file placed.The disk reference is optional; if present it is of theform A:, B:, etc.

The following command will compile the programINVENTORY. BAS taking the source from the currentlyselected drive, and place the INT file on drive B:

CBAS2 INVENTORY B:

If a listingthe program ascharacters up towill appear inFor instance:

is selected (section 13.2), the name ofit appears following CBAS2 and any other

the dollar sign or end of the commandthe heading of each page of the listing.

CBAS2 COST ON 7 NOVEMBER 1980 $EBF

will result in the following heading:

CBASIC COMPILATION OF COST ON 7 NOVEMBER 1980

8

Page 16: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 General Information

The sourc~~ program is normally listed on the consoledevice. Any error messages will be listed after thestatement in ''''hich the error was detected (see section13.3). If errors are detected during compilation, thesource file must be corrected using the text editor. Thecompil~r error messages are listed in appendix A. Theprogram is th~~n recompiled. If no errors occur duringcompilation, the intermediate file may be executed bytyping the command:

CRUN2 <filename> [TRACE [<lnl>[,<ln2>]]] [<clOd>]

The trace option is described in chaptercommand field «clOd» is used with thepre-defined function discussed i.n chapter 7.

13. TheCOMMAND$

If errors are found durin.g execution, the sourceprogram must be corrected and. then recompiled. Runtimeerror messagel; are described in appendix B.

9

Page 17: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

3. FORMING EXPRESSIONS

Forming Expression

This chapter discusses the formation of expressions. ....JFirst the components of expressions, constants and variables,are described. These elements are then combined to formexpressions;. Expressions are a fundamental building blockused in many CBASIC statements.

3.1 Stri.ngs

A string constant is defined as zero or more validalphanumeric characters enclosed by quotation marks (II).Since a. continuation character is treated as part of thestring, strings defined as constants in the source programmust be contained on a single line. A carriage return maynot bE,' part of a string. Embedded quotation marks areentered as two adjacent quotes.

The followingconstants:

11123 11

examples demonstrate valid string

·'Ju1y 4, 1979 11

IIEnter your name please II

II "'IILook, look,lIl1 said Tom ll

In the final example the string is:

"l,ook, look, II said Tom

Int.ernal1y, strings are stored with the length of thestring as the first byte. The characters of the stringfollow. The length is stored as a binary number from 0 to255.

3.2 Numbers

Two types of numeric quantities are supported byCBASIC, Integer and Real. A real constant may be writtenin either fixed format or exponential notation. In bothcases it may contain from 1 to 14 digits, a sign, and adecimal point. In exponential notation the exponent is ofthe form IIEsdd ll

, where 's', if present, is a valid sign(+, -, or blank) and where 'dd' is one or two validdigits. The sign is the sign of the exponent and shouldnot be confused with the optional sign of the mantissa.

10

Page 18: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

The numbers range from 1.~E-64 to 9.9999999999999E62.Although only 14 significant digits ,are maintainedinternally by CBASIC, more digits may be included in areal constant. Real constants are rounded to 14significant digits.

Real numbers are stored in eight bytes of memory. Thefirst byte is the sign and exponent. The exponent ismaintained in excess 64 code. The seven remaining bytescontain a normalized mantissa stored as packed decimaldigits. The high order four bits of the rightmost byte isthe most significant digit of the mantissa.

If a constant does not contain an embedded decimalpoint, is not in exponential notation, and ranges from-32768 to +32767, the constant is treated as an integer.Integer values are stored as sixteen bit two·s complementbinary numbers.

Integer constants may also be expressed as hexadecimaland binary constants. If the constant is terminated bythe letter H it is hexadecimal. The letter B terminates abinary constant. The first digit of a hexadecimalconstant must be numeric. For instance 255 in hexadecimalwould be ~FFH, not FFH. FFH would be a valid identifier(see section 3.3).

Binary and hexadecimal constants may not contain adecimal point. The value retained is the sixteen leastsignificant bits of the number specified.

In this manual the term real number and floating pointnumber will be used interchangeably. The term numericwill apply to either a real or integer quantity.

Examples of valid numbers are:

1, l.~, -99, 123456.789

1.993, .~l, 4E12, 1.77E-9

1.5E+3 is equivalent to l5~~.~

1.5E-3 is equivalent to .~~15

lab~H, l~lllll~B, ~FFFFH

11

Page 19: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

3.3 Identifiers

Forming Expression

An identifier begins with an alphabetic characterfollowed by any number of alphanumeric characters or ~..Jperiods. Identifiers identify or name variables usedwithin a program. Only the first 31 characters areconsidered unique, however the identifier may be of anylength. If the last character in the identifier is adollar s:ign, the identifier is of type string. If theidentifier ends in a percent sign, it represents aninteger. Those identifiers not ending with a dollar signor percent sign are of type real.

All lower case letters appearing in an identifier areconvertE!d to upper case unless compiler toggle D is set(Chapter 13). Using periods in identifiers make programsmore rE!adable. For instance BAD. DEBT% is clearer thanBADDEBT~;.

Using identifiers which are longer than two charactersimproves: program readability without increasing the sizeof the i.ntermediate file created by the compiler.

Examples: of valid identifiers are:

A, B$, cl, c1234%

Payroll.Record, NEW.SUM.AMT

INDEX%, FLAG.3%, counter%

ANSWER$, file.name$, CUSTOMER.ADDRESS$

3.4 Variables and Subscripted Variables

The general form of a variable is:

<i~Emt.ifie:r) [«$ubsc~i.pt. list) ) J

The general form of a sUbscript list is:

<e~pression) { , <expression> }

The expressions in a subscript list must be numeric.Access to array elements is more efficient if integerexpressi.ons are used in subscript lists. If theexpressi.on is real, the value is rounded to the nearestinteger prior to using the value. If an expression in asUbscript list is of type string, an error occurs. Thesubscript list indicates that the variable is a

12

...J

Page 20: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

sUbscripted variable and indicates which element of thearray is being referenced.

Each variable has a value associated with it at alltimes durin9 execution of a program. Initially numbersare zero and strings are null strings. A string variabledoes not have a fixed length associated with it. Rather,as different strings are assigned to the variable, thestorage is dynamically allocated. The maximum lengthwhich may lbe assigned to a. string variable is 255characters.

The iden,tifier used to represent a variable may notbegin with l~N. Such identifie:rs are used to specify userdefined functions (See chapter 8).

A variable in CBASIC may representnumber, or a string depending onidentifier.

Examples of variables are:

X$PAYMENTday.of.deposit%

anthe

integer,type of

realthe

The followin9 examples show subscripted variables:

y$(i%,j~~)

COST(3,S)

POS%(XAXIS%,YAXIS%)

INCOME(J~T(CLIENT%),CURRENT.MONTH%)

When subscripts are calculated, a check is made toensure that 1:he element selected resides in the referencedarray. A runtime error occurs if it does not. Theruntime check insures that the location calculated isincluded wi1:hin the physical storage area of the array.It is not necessarily a valid entry.

Before a subscripted variable may be referenced in aprogram, it must be dimensioned using the DIM statement.The DIM sta1:ement specifies the upper bound of eachsubscript and allocates storage for the array.

13

Page 21: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

A DIM statement is an executable statement: eachexecution will allocate a new array. If the arraycontains numeric data the previous array is deleted priorto allocating space for a new array. If the array is of ,~.J

type st~ring each element must be set to a null stringprior to re-executing the DIM statement to regainthe ma:ltimum amount of storage. The general form of aDIM statement is:

~<:stmt nwnbe~>Jf

«subscript list», 'bscri.pt. list»}

The dimension statement dynamically allocates spacefor nl~eric or string arrays. Elements of string arraysmay be any length up to 255 bytes, and change in lengthas they assume different values. Initially numeric arraysare set to zero and all elements of string arrays are nullstringB.

An array must be dimensionedoptionf;; are provided. Arraysorder.

explicitly: no defaultare stored in row-major

ThE;! subscript list is used to specify the number ofdimensions and the extent of each dimension of the arraybeing c:leclared. The subscript list may not contain areference to the array being dimensioned.

ExampIE;!S of DIM statements:

All subscripts have an implied lower bound of zero..J

DIM A( UJ)

DIM ACCOUNT$(100),ADDRESS$(100),NAME$(100)

DIM B%(2,5,10), SALES.PERSON%(STAFF.SIZE%)

DIM X(A%(I%),M%,N%)

ThE;! same identifier may be used as both a variable andas a subscripted variable within the same program.

14

Page 22: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

\ .'--

3.5 Expressions

Expressions consist of algebraic combinations offunction references, variables, constants, and operators.They evaluate to an integer, real, or string value.Function references are discussed in chapter 8. Thehierarchy of operators is:

1) nested parenthesis ()2) A power operator3) *, /4) +, -, concatenation (+), unary +, unary -5) relational operators <, <=, >, >=, =, <>

LT, LE, GT, GE, EQ, NE6) NOT7) AND8) OR, XOR

Arithmetic and relational operations may be performedon either integer or real numbers. If an integer and realnumber are to be combined using one of these operators,the integer value is. first converted to a real number.The operation is then performed on the two real valuesresulting in a real value. This is referred to as mixedmode arithmetic.

Mixed mode operations take additional time to executeand the compiler generates more code. A mixed modeexpression will always evaluate to a real value.

If real values are used, the power operator calculatesthe logarithm of the number being raised to the power.Since the logarithm of a negative number is undefined, awarning results when the number to the left of theoperator is negative. The absolute value of the negativequantity is used to calculate the result. The exponentmay be either positive or negative.

If both values used with the power operator are eitherinteger constants or integer variables, the result iscalculated by successive multiplication. This allows anegative integer number to be raised to an integer power.In the case of integers, if the exponent is negative, theresult is zero. In all cases, 0 A 0 is 1 and 0 A X (whenX is not equal to 0) is 0.

If the exponent is an integer but thethe integer is converted to a realcalculating the result. Likewise, if thebut the base is an integer quantity,calculated using real values.

15

base is real,value prior toexponent is realthe result is

Page 23: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

String variables may only be operated on by relationaloperators and the concatenation operator. Mixed stringand numeric operations are not permitted. The mnemonic _Jrelational operators (LT, LE, etc.) are interchangeablewith the corresponding algebraic operators «, <=, etc.).

Exampll:!s of expressions:

amount * tax

cost + overhead * percent

last.name$ + ", " + first.name$

index% + 1

Relational operators result in integer values. A 0 isfalse and a -1 is true. Logical operators NOT, AND, OR,and XOR operate on integer values and result in aninteger number. If a real value is used with logicaloperators it is first converted to an integer.

If a numeric quantity is greater than 32,767 or lessthan -32,768, it cannot be represented by a 16 bit two'scomplement binary number. Logical operations on such anumber will give unpredictable results.

Results of logical operations:

1 ~, AND 3 = fJ IlfJfJB AND 0lfJlB = 4~.

NOT -1 = 0 NOT 3H = -4

1 ~, OR 3 = 15 0CH OR 5H = 13~,

1 ''I XOR 3 = 15 12 XOR 5 = 9.I.,

12.4 XOR 3.2 = 15 12.4 XOR 3.7 = 8

By using integer expressions for relational tests andlogical operations a substantial increase in efficiencyresults,. Programs written in version 1 of CBASIC shouldbe converted to use integer variables where everpossible.

ThE~ following point should be understood about numericconstants. If the string of digits contains no decimalpoint or ends in a decimal point, CBASIC attempts to store

16

Page 24: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

it as an integer. If the resulting number is in the rangeof CBASIC integers, it is treated as an integer. If theconstant is then required in an expression as a realnumber, a conversion to a real number occurs at runtime.For instance:

x = X + 1.

would cause the integer constant 1.real value prior to adding it to X.can be eliminated by embeddingnumber as shown below:

X = X + 1.0

to be converted to aThis extra conversion

the decimal within the

In actual practice there is very littleexecution speed. A similar situationfollowing statement:

Y% = X% + 1.0

differenceexists in

inthe

In this case the X% is converted to a real number prior tothe addition to the real constant. The result is thenconverted back to an integer prior to assignment to Y%.

In general, the programmer should avoid mixed modeexpressions when possible, and should not use realconstants with integer variables. Most whole numbers usedin a program will be stored as integers. This normallyprovides the most efficient execution.

If an overflow occurs duringvalues, a warning is printed andthe result of the operationnumber.

an operation between realexecution continues withset to the largest real

In the case of integers no checking for overflow isperformed since this would reduce the efficiency ofinteger operations. It should be understood that if theresults of an integer operation fall outside the range ofinteger values, the calculated value will be incorrect.

3.6 Assignment Statements

[~stmt number>] [LET] <variable> = <expression>

The expression is evaluated and assigned to thevariable appearing on the left side of the equal sign.The variable and expression must either both be of typestring or both be a numeric type.

17

Page 25: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Forming Expression

If the variable and expression are bothone is integer and the other is real,conversion to the type of the the variable onthe equal sign is performed.

Examples:

100 LET A = B + C

X(3,POINTER%) = 7.32 * Y + X(2,3)

numeric butan automaticthe left of

SALARY = (HOURS.WORKED * RATE) - DEDUCTIONS

date$ = month$ + It It + day$ + It It + year$

INDEX% = INDEX% + 1

RE:C . NUMBER = OFFSET% + NEXTREC%

18

Page 26: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

4. CONTROL STATEMENTS

4.1 GOSUB Statement

Control Statements

[<st.mt

[<stmt

The location of the next sequential instruction issaved on the return stack. Control is then transferred tothe statement labeled with the statement number followingthe GOSUB.

Subroutine calls may not be nested greater than 20deep.

Examples:

GOSUB 700

REM PRINT THE TABLEFOR INDEX% = 1 TO TABLE.SIZE%

PRINT TABLE(INDEX%)NEXT INDEX%RETURN

PRINTGOSUBPRINTSTOP200

"BEFORE TABLE"200 REM PRINT THE TABLEIIAFTER TABLE"

4.2 RETURN Statement

The RETURN statement causes the execution of theprogram to return to the statement that immediatelyfollows the most recently executed subroutine call. Thatis, execution continues at the location at the top of thereturn stack. The call may be a GOSUB statement, ON .•GOSUB statement, or multiple line function call. SeeChapter 8 for a discussion of mUltiple line functions.Refer also to section 4.12 for information on the effectof CHAINING on subroutine linkage.

If a return is executed without previously executing aGOSUB, ON ..•GOSUB, or multiple line function call, aruntime error occurs.

19

Page 27: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

Examples:

500 RETURN

IF ANSWER.VALID% THEN RETURN

4.3 GOTO Statement

Control Statements

If thestatementsexecuted.ELSE isstatement

Execution continues at the statement labeled with thestatement number following the GOTO or GO TO; If thestatement number branched to is not an executablestatement, execution continues with the next executablestatement after the statement number.

If the statement number to which control is beingtransferred does not exist, an error will result.

Examples:

80 GO TO 35

GOTO 100.5

4.4 IF Statement

value of the expression is not zero, thewhich make up the first statement list are

Otherwise, the statement list following theexecuted, if present, or the next sequentialfollowing the IF statement is executed.

In the second form of the IF statement, when theexpression is not equal to zero, an unconditional branchto the statement number occurs. Note that this form ofthe IF' statement may not have an else clause. Thisvariation is included in CBASIC for compatibility withprevious versions of Basic.

20

Page 28: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

......._-

The expression in an IF statement will normally be alogical expression. That is, it evaluates to either true(-1) or false (0). However, CBASIC will accept anynumeric expression treating a value other than zero astrue. The expression should be of type integer. Thiswill reduce execution time and also reduce the size of theintermediate file generated by the compiler. If theexpression is real, the value is rounded and converted toan integer. A string expression will result in an error.

A statement list is composed of one or morestatements in which each pair of statements is separatedby a colon (:). The colon is not required after the THENnor is it required before or after the ELSE. It is onlyused to separate statements. An IF statement must be thefirst statement on a line; it may not follow a colon. Inother words IF statements may not be nested.

Examples:

IF ANSWER$= t1 YES" THEN GOSUB 500

IF DIMENSIONS.WANTED% THEN PRINT LENGTH, HEIGHT

IF VALID% THEN \PRINT MSG$(CURRENT.MSG%) :\GOSUB 200 :\ UPDATE RECORDGOSUB 210 :\ WRITE RECORDNO.OF.RECORDS%=NO.OF.RECORDS%+l :\RETURN

IF X > 3 THEN X = 0 : Y = 0 : Z = 0

IF YES% = TRUE% THEN PRINT MSG$(l) \ELSE PRINT MSG$(2)

IF TIME>LIMIT THEN \PRINT TIME.OUT.MSG$ :\BAD.RESPONSES% = BAD.RESPONSES%+l :\QUESTION% = QUESTION%+l \

ELSE \PRINT THANKS.MSG$ :\GOSUB 1000:\ ANALYSE RESPONSEON RESPONSE% GOSUB \

2000, 2010, 2020, 2030, 2040 :\RETURN

In the examples above, note that the colon (:) is usedto separate statements within a statement list and thebackslash (\) is used to continue a statement onto anotherline.

21

Page 29: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

Since the compiler ignores anything following and onthe same line with the backslash, comments may be insertedwithout: using the keyword REM. _...J

4.5 WHILE Statement

n~.~~

EXE~cution of all statements between the WHILEstatemEmt and its corresponding WEND is repeated until thevalue of the expression is zero. If the value is zeroinitially the statements between the WHILE and WEND willnot bE~ executed. Variables used in the WHILE expressionmay chcmge during execution of the loop.

ThE! expression should be of type integer. This willreduce execution time and also reduce the size of theintermE!diate file generated by the compiler. If theexpreselion is real, the value is rounded and thenconverted to an integer. A string expression will resultin an E!rror.

4.6 WEND Statement

A WEND statement denotes the end of theunmatched WHILE statement. A WEND statementpresent:. for each WHILE statement in a program.

closestmust be

..J

Bra.nching to a WEND statement is the same as branchingto its corresponding WHILE statement.

Example!s:

WHILE -1PRINT "X"

WE:ND

WHILE X > ZPRINT XX = X-I."

WE::ND

22

Page 30: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

TIME = 1lJ.1lJTlME.EXPlRED% = FALSE%WHILE TIME < LIMIT

TIME = TIME + 1.1lJIF CONSTAT% THEN \

RETURN REM ANSWERED IN TIMEWENDTIME.EXPlRED% = TRUE%RETURN

WHILE ACCOUNT.IS.ACTIVE%GOSUB lllJllJ REM ACCUMULATE INTEREST

WEND

WHILE FILE.EXISTS%WHILE TRUE%

IF ARG$ = ACCT$ THEN '\ACTIVITY% = TRUE% :\RETURN

IF ARG$ < ACCT$ THEN '\ACTIVITY% = FALSE% :\RETURN

GOSUB 31lJ1lJ1lJ REM READ ACCT$ RECWEND

WENDACTIVITY% = FALSE%RETURN

WHILE TRUE%INPUT LINE STRING$IF STRING$ = CONTINUE$ THEN RETURN

WEND

4.7 FOR Statement

Execution of all statements between the FORand its corresponding NEXT statement is repeatedindexing variable, which is incremented byexpression after each iteration, reachescriteria.

statementuntil thethe STEP

the exit

If the step expression is posi,tive, the loop exitcriteria is met when the index exceeds the value of the TOexpression. If the step expression is negative, theindex must be less than the value of the TO expression forthe exit criteria to be satisfied.

23

Page 31: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Versi()n 2 Control Statements

It isBoth

loop:change

T1H:! index must be an unsubscripted variable.initially set to the value of the first expression.the TO and STEP expressions are evaluated on eachall variables associated with these expressions maywithin the loop.

Additionally, the index may be changed duringexecution of the loop. The type of the index and allexpresnions should be the same. They may be either realor in1:eger. I f any of the expressions are of typestring ,I' an error occurs. Particular care should be takento innure proper matching of the expression types. Forinstance:

FOR 1% = 1 to DONE

will gEmerate unneccessary code because DONE is real but1% and 1 are integers. A more subtle example is:

FOR I = 1. to DONE

In thif:; case I and DONE are real but 1. is an integer.

There is one situation when a FOR statementthat appears to be valid will generate a compilererror "FE". This occurs if the type of the express10nfollowing the TO is not the same as the type of theloop index variable.

For exa.mple:

FOR I = 1 TO 13 STEP 3

results. in an error "FE" because the index variable I isreal l::,ut the value following the TO is an integer.Changing the index to 1% will eliminate the error.

If the STEP clause is omitted, a default value of oneis assumed. The type of the STEP expression in this casewill be the same as the type of the index.

The statements within a FOR loop are always executedat least once. Examples:

FOR INDEX% = 1 TO l~

SUM = SUM + VECTOR(INDEX%)NEXT INDEX%

FOR POSITION=MARGIN+TABS TO PAPER. WIDTH STEP TABSPRINT TAB(POSITION):SET.TAB$:

NEXT POSITION

24

.J

Page 32: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

If a step of one is desired, theomitted. The execution will be muchruntime checks will be made.intermediate code is produced.

Control Statements

STEP clause should befaster since fewerIn addition, less

'--'

The speed of execution will also be substantiallyimproved if all the expressions are ()f type integer.

4.8 NEXT Statement

C'••t.'i'i.~r>c1

A NEXT statement denotes the end of the closestunmatched FOR statement. If the optional identifier ispresent, it must match the index variable of the FORstatement being terminated.

The list of identifiers allows terminating mUltipleFOR statements. The statement numbE~r of a NEXT statementmay appear in an ON or GOTO statement, in which caseexecution of the FOR loop continues with the loopvariables assuming their current values.

The following example of nested l~OR loops shows theuse of a list of identifiers:

FOR 1% = 1 TO 10FOR J% = 1 TO 20

X(I%,J%) = 1% + J%NEXT J%, 1%

The final example shows the use ()f a NEXT statementwithout an identifier.

FOR LOOP% = 1 TO ARRAY.SIZE%GOSUB 200GOSUB 300

NEXT

4.9 ON Statement

[<stmt~num~:r>

I[<stmttnWmH!r>.~y,~

! nUJIlbelc->

25

Page 33: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

ThE! expression is used to select the statement numberat whi.ch execution will continue. If the expressionevaluat~es to 1, the first statement number is selected,and SCI forth. In the case of an ON ••. GOSUB statement the ,~J

address; of the statement following the ON statement issaved on the return stack. A runtime error occurs if theexpress:ion is less than one or greater than the number ofstatemE!nt numbers in the list.

ThE! expression must be numeric. A string expressionwill grenerate an error. Integer expressions will improveexecution speed. If a real value is used, it is roundedto thE! nearest integer prior to selecting the statementnumber to branch to.

ThE! keywords GOTO and GOSUB may alternately be codedas GO 1.'0 and GO SUB.

Examples:

O~ 1% GOTO 10, 20, 30

ON J% - 1 GO SUB 12.10, 12.20, 12.30, 12.40

WHILE TRUE%GOSUB 100 REM ENTER PROCESS DESIREDGOSUB 110 REM TRANSLATE PROCESS TO NUMBERIF PROCESS.DESlRED% = 0 THEN RETURNIF PROCESS.DESlRED% < 6 THEN \

ON PROCESS.DESlRED% GOSUB \1000, \ ADD A RECORD1010, \ ALTER NAME1020, \ UPDATE QUANTITY1030, \ DELETE A RECORD1040, \ CHANGE COMPANY CODE1050 \ REM GET PRINTOUT

ELSE GOSUB 400 REM ERROR - RETRYWEND

4.10 STOP Statement

When a STOP statement is encountered, programexecution terminates. All open files are closed, theprint buffer is emptied and control returns to the hostsystem. Any number of STOP statements may appear in aprogram.

26

Page 34: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

A STOP statement is appended to all programs by thecompiler.

Examples:

400 STOP

IF STOP.REQUESTED THEN STOP

4.11 RANDOMIZE Statementi

[ <stmt In.\1mber> ]

The RANDOMIZE statement initializes or seeds therandom number generator. The time taken by the operatorto respond to an INPUT statement (chapter 5) is used toset the seed. This time will vary with each execution ofa program. Therefore, for RANDOMIZE to work correctly, itmust be preceded by an INPUT statement.

The configuration 3 runtime package uses the real-timeclock to seed the random number generator when operatingunder MP/M.

Examples:

450 RANDOMIZE

RANDOMIZE

4.12 CHAIN Statement

[<st.mtJnumber~,The CHAIN Statement transfers control from the

program currently being executed t() the program selectedby the expression. The expression must be of type stringor an error will occur. The expression must also evaluateto any unambiguous file name. A file with that name andof type INT must reside on the specified drive. If nodrive is specified, the currently logged-in drive is used.In the discussion on chaining the' first program executedis the main program.

27

Page 35: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

The following statement:

.....Jstatementon driveof INT

CHAIN "B:PAYROLL"

cause execution to continue with the firstthe program PAYROLL. PAYROLL.INT must resideRegardless of the file type specified, a type

is forced.

willinB.

The CBASIC runtime monitor main.tains four partitionsin memory. They are designated t.he constant, code, datastatement, and variable areas. The size of these areas isdetermined by the compiler. If in a chained program oneor more of these areas is larger than that correspondingarea in the original or main program, a runtime erroroccurs. In other words the main program constant, code,data statement, and variables areas must be as large orlarger than any corresponding area in a program that issubsequently chained. If this is not the case, theprogrammer must use the %CHAIN compiler directive toadjust the size of the main programs partitions. The%CHAIN directive is discussed in Chapter 12.

In order to determine the size of each partition in aprogram the compiler produces a table of these valuesafter each compilation. The values include the effect ofthe %CHAIN directive if present. The %CHAIN directiveneed only be used in the main program. The relationshipof partition size between programs chained is notsignificant.

A CHAIN statement may appear in any program. Aprogram may chain back to the program which invoked it, toa new program, or to itself. If a STOP statement isexecuted in any program, execution stops and control isreturned to CP/M.

Upon execution of a CHAIN statement the return stackis reset. All open files are closed and a restore isperformed. Data may be passed from one program to anotherusing the COMMON statement discussed below.

4.13 COMMON Statement

[<stm~ :nUInber>]CO~ <variable> }

If present, COMMON statements must be the firststatements in a program except that blank lines and REMstatements may precede COMMON statements. A COMMON

28

Page 36: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

statement is a non-executable statement and specifies thatthe variables listed will be common to the main programand all programs executed through a CHAIN statement.

If the main program contains COMMON statements, eachchained program must have COMMON statements that match theCOMMON statements in the main program. Matching meansthat there are the same number of variables in each COMMONstatement and, that the type of each variable in the mainprogram's COMMON statement matches the type of eachvariable in the chained program's COMMON statement.Also, dimensioned variables must have the same number ofsubscripts in each program.

Subscripted variables are specified by placing thenumber of subscripts in parenthesis following the arrayname. For instance:

COMMON X, Y, A(3), B$(2)

specifies that X and Yare nonsubscripted real variablesand will be common to all chained programs. A and B$ arearrays which may be accessed by all programs. A has threesUbscripts while B$ has two. The COMMON Statement doesnot indicate the size of any subscript.

The specification of an array in a COMMON statement isnot, in general, the same as the specification in a DIMstatement. This point must be cllearly understood. Forexample:

COMMON A(3)

might be used with

DIM A(20,30,20)

but if it was used with

DIM A(3)

an error would occur.

Prior to accessing an element in an array in COMMON,the array must be created using the DIM statement.Failure to do this will lead to catastrophic resultslThe first program requiring acceliiS to the array shouldinsure that a DIM statement is executed specifying thedesired range for each sUbscript. Subsequent programs mayaccess this array with the data remaining unchangedthrough the chaining process. If a subsequent program

29

Page 37: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Control Statements

executes a DIM statement for this array, the data in thearray will be lost. In other words the array will bere-ini1:ialized. However, in the case of stringarrays, elements in the array will not be freed from ,~J

memory. The programmer should set elements of stringarrays to null strings prior to executing a second DIMstatement for the array.

30

Page 38: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Input/Output Statements

5. INPUT/OUTPUT STATEMENTS AND FUNCTIONS

5.1 General Information

This chapter introduces input and output statementsand functions. File accessing statements are discussed inchapter 10; formatted printing is explained in chapter 9.

CBASIC prints each character as it is generated. Ifthe length of the line being printed exceeds the width ofa print line, printing continues on 1:he next line. Thatis, a carriage return and a linE!feed are output. Thewidth of the print line may be controlled by the user.

Input from the console is read a line at a timeinstead of a character at a time. ~lis allows the user totake advantage of the CP/M line-·editing functions. Acontrol-C entered from the keyboard ~nay return the user toCP/M without closing open files.

In this manual console refers to the physical deviceassigned to the CP/M logical device CON:. Likewise thelist device refers to the physical unit assigned to theCP/M logical device LST:. For more information on logicaland physical devices refer to 1:.he Digital Researchpublication "An Introduction To CP/M Features andFacilities."

.......- 5.2 PRINT Statement

[stmt t~

The PRINT statement outputs 1:.he value of eachexpression to the console unless an LPRINTER statement(described below) is in effect. In t.he latter case outputis directed to the list device (see l:lection 5.3). If thelength of a numeric item would rel:lult in the line widthbeing exceeded, the number to be printed begins on thenext line. Strings are output until the line width isreached and then the remainder of th4~ string, if any, isoutput on the next line.

The delimiter between expressions may be either acomma or a semicolon. The comma causes automatic spacingto the next column that is a multiple of 20. If thisspacing results in a print posi'tion greater than thecurrently specified width, printing (:ontinues on the nextline. A semicolon causes one blaru~ to be output after anumber and no spacing to occur after a string.

31

Page 39: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Input/Output Statements

5.3

A carriage return and a linefeed are automaticallyprinted when the end of a print statement is encounteredunless the last expression is followed by a comma or a ,~Jsemicolon. These partial lines are not terminated untilone of the following conditions occur: (1) another PRINTwhose list does not end in either a comma or semicolon isexecutE~d, (2) the line width is exceeded, (3) an LPRINTERor CONSOLE statement is executed, or (4) the programexecutes a stop statement. A PRINT statement with noexpression list will cause a carriage return and alinefeed to be printed.

If execution of a program is terminated due to anerror, a carriage return and a linefeed are output.

ExamplE!s:

PRINT

PRINT AMOUNT.PAID

PRINT QUANTITY, PRICE, QUANTITY * PRICE

PRINT "TODAY' S DATE IS: ": MONTH$: II ": DAY%: ", ": YEAR%

LPRINTER Statement

[stInt Inumber> ].:[,~~II11':ER [WXPTU <eXMest5ion>]

After execution of the LPRINTER statement all PRINTstatement output, which would normally be directed to theconsole, will be output on the list device. The listdevice is the physical unit currently assigned to LST: byCP/M. The WIDTH clause is optional. If present theexpression will be used to set the line width of the listdevice.

If the console's cursor position is not 1, a carriagereturn and linefeed is output to the console. In thiscontext the cursor position is the value that would bereturned by the POS function (see section 5.5) just priorto executing the LPRINTER statement.

The expression should be of type integer. If it isreal, the value is rounded to an integer. An error occursif the expression is of type string.

32

Page 40: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Input/Output Statements

If the width option is not present, the most recentlyassigned width is used. Initially the width is set to132. A width of 0 will result in an infinite line width.With a zero width in effect carriage returns and linefeedsare never automatically output to the printer as a resultof exceeding the line width.

Examples:

500 LPRINTER

IF HARDCOPY.WANTED% THEN LPRINTER WIDTH 120

LPRINTER WIDTH REQUESTED.WIDTH%

5.4 CONSOLE Statement

[stmt number>] CQNSQ~~

Execution of the CONSOLE statement restores printedoutput to the console. the console is the physical unitcurrently assigned to CON: by CP/M.

If the list device print position is not 1, a carriagereturn and linefeed are output to the list device.

Examples:

490 CONSOLE

IF END.OF.PAGE% THEN \CONSOLE :\PRINT USING "##,### WORDS THIS PAGE":WORDS% :\INPUT "INSERT NEW PAGE, THEN CR":LINE TRASH$ :\LPRINTER

The width of the console device may be changed withthe POKE statement (Chapter 6). The console width is onebyte at location 272 base 10 or l10H. The new consolewidth will become effective at the next execution of aCONSOLE statement. The console line width is initiallyset to 80 (50H).

A width of zero (0) results in an infinite width.With a zero width in effect, carriage returns andline feeds are never automatically output to the console asa result of exceeding the line width.

33

Page 41: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

5.5 POS Pre-defined Function

POS

Input/Output Statements

POS returns the next position to be printed on eitherthe console or the line printer. This value will rangefrom 1 to the line width currently in effect.

If a LPRINTER statement is in effect, POS will returnthe next position to be printed on the printer. Note thatPOS returns the actual number of characters sent to theoutput device. If cursor control characters aretransmitted, they are also counted even though the cursoris not advanced.

Examples:

PRINT liTHE PRINT HEAD IS AT COLUMN: ": POS

IF (WIDTH.LINE - POS) < 15 THEN PRINT

5.6 TAB Pre-defined Function

TAB «expression»

TAB causes the cursor or print head to be positionedto a position specified by the value of the expression.If the value of the expression is less than or equal tothe current print position, a carriage return and linefeedare output and then the tab is executed.

The TAB function is implemented by outputting blankcharacters until the desired position is reached. Ifcursor or printer control characters have been output, thecursor or print head could be positioned incorrectly.

The TAB function may onlystatements.

be used in PRINT

The expression must be numeric. If a stringexpression is specified, an error occurs. If theexpression is real, it is first rounded to an integer.If the expression is greater than the current line width,an error occurs.

34

Page 42: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

Examples:

PRINT TAB(15)i I X"

Input/Output Statements

PRINT "THIS IS COL. l"iTAB(5121)i"THIS IS COL. 5121"

PRINT TAB(X%+Y%/Z%)i l l"iTAB(POS%+OFFSET%)i

PRINT TAB(LEN(STR$(NUMBER»)i l *"

5.7 READ Statement

(stmt

5.8

A READ statement assigns values from DATA statementsto the variables. DATA statements are processedsequentially as they appear in the program. An attempt toread past the end of the last DATA statement produces aruntime error.

Examples:

READ NAME$,AGE%,EMPLOYER$,SSN

FOR PROD.NO% = I TO NO.OF.PRODUCTS%READ PRODUCT.NAME$(PROD.NO%)

NEXT PROD.NO%

DATA Statement

[stmt Jumber»i

DATA statements are nonexecutable statements whichdefine string, floating point, and integer constants whichare assigned to variables using a READ statement. Anynumber of DATA statements may occur in a program. Theymay be placed anywhere in the program.

The constants are stored consecutively in a data areaas they appear in the program and are not syntax checkedby the compiler. Strings may be enclosed in quotationmarks or optionally delimited by commas.

A DATA statement must be the only statement on a lineand it may not be continued with a continuation character.However, all DATA statements in a program are treatedcollectively as a concatenated list of constants separatedby commas.

35

Page 43: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

Examples:

Input/Output Statements

400 DATA 332.33, 43.0089E5, "ALGORITHM"

DATA ONE, TWO, THREE, 4, 5, 6

In the second example ONE, TWO and THREE are strings.

If a real constant is assigned to an integer variablewith Cl READ statement, the constant is rounded off tothe integer portion of the real number. If the valueof a number assigned to an integer is outside therange of CBASIC integers, incorrect values will beassigned. If a real number exceeds the range of realnumbers, an overflow warning occurs and the largestCBASIC number is used in its place.

5.9 RESTORE Statement

[st..trn~.r)l~iRES'r08S

A RESTORE statement repositions the pointer into thedata area so that the next value read with a READstatement will be the first item in the first DATAstatement.

.......J

The purpose of a RESTORE statement is to allowre-reading the constants contained in DATA statements. .,J

Examples:

500 RESTORE

IF END.OF.DATA% THEN RESTORE

When a CHAIN statement is executed a RESTORE isperformed.

5.10 INPUT Statement

[stmt. nwnber>]IBP~<variable

If the prompt string is present, it is printed on theconsole, otherwise a question mark is output. In bothcases a blank is then printed and a line of input data isread from the console and assigned to the variables asthey appear in the variable list.

36

Page 44: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Input/Output Statements

The variables may be either simple or subscriptedstring or numeric variables.

At most 255 characters may be entered in response toan INPUT statement. If 255 or more characters areentered, inputing is automatically terminated and thefirst 255 characters are retained. Additional characterswill be lost. The 255 characters include allcharacters entered in response to an input statement nomatter how many variables appear in the variable list.

All CP/M line editing functions such as control-U andrubout are in effect. A control-C may terminate theprogram without closing open files. If a control-Z is thefirst character entered in response to an INPUT statementthe program is terminated in the same manner as if a STOPstatement had been executed.

at the console must beterminated by a carriagein quotation marks in

blanks may be included in

The data items enteredseparated by commas and arereturn. Strings may be enclosedwhich case commas and leadingthe string.

The prompt string must be a string constant. If it isan expression or a numeric constant, an error occurs.

If the value entered for assignment to an integer isreal, the number entered is truncated to the integerportion of the real number. If the value of a numberassigned to an integer variable is outside the range ofintegers, an incorrect value will be assigned. If a realnumber exceeds the range of CBASIC real numbers, thelargest real number is assigned to the variable, and awarning is printed on the console.

If too many or too few data items are entered, awarning is printed on the console, and the entire linemust be re-entered.

Examples:

INPUT AMOUNTI, AMOUNT2, AMOUNT3

INPUT "WHAT FILE, PLEASE?":FILE.NAME$

INPUT ItYOUR PHONE NUMBER PLEASE:": PHONE.N$

INPUT nlt:ZIP.CODE%

37

Page 45: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Input/Output Statements

A special type of INPUT statement is the LINE INPUT.The general form of this statement is:

[s~ qumb.r~~~«pr~~1 LIbfE <variable>

This statement functions as described above with thefollowing exception. Only one variable is permittedfollowing the keyword LINE. It must be of type string.Any data entered from the console is accepted and assignedto this variable. The data is terminated by a carriagereturn.

A null string may be accepted by responding to anINPUT LINE Statement with a carriage return.

An error occurs if the variable specified to receivethe input is not of type string.

Examples:

INPUT II ENTER ADDRESS II : LINE ADDR$

INPUT "TYPE RETURN TO CONTINUE";LINE DUMMY$

Prompt strings are directed to the console even whenan LPRINTER statement is in effect.

5.11 OUT Statement

[StIntfnumber»OU expression>

The low-order eight bits of the second expression aresent to the CPU output port selected by the low-ordereight bits of the first expression.

Both arguments must be numeric; they should be in therange of ~ to 255 for the results to be meaningful. Anerror occurs if either expression is of type string. Realvalues are converted to integers prior to performing anOUT instruction. Examples:

OUT 1,58

OUT FRONT.PANEL%, RESULT%

IF X% > 5 THEN OUT 9, «X*X)-1.)/2.

OUT TAPE.DRIVE.CONTROL.PORT%, REWIND%

OUT PORT%(SELECTED%), ASC("$")

38

Page 46: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

5.12 INP Pre-defined Function

\ INP «expression»,,--

Input/Output Statements

INP returns the value input from the CPU 1/0 portspecified by the expression. This function is useful foraccessing peripheral devices directly from the CBASICprogram.

The argument must be numeric. An error occurs if itis a string. A real value will be rounded to the nearestinteger. For the results to be meaningful, the argumentmust be in the range of 0 to 255.

Examples:

PRINT INP(ADDR%)

IF INP(255) > 0 THEN PRINT CHR$(7)

ON INP(INPUT.DEVICE.PORT%) GOSUB \100, 200, 300, 400, 400, 400, 500

5.13 CONSTAT% Pre-defined Function

CONSTAT%

CONSTAT% returns the console status as an integervalue. If the console device is ready, a logical true isreturned otherwise a logical false is returned.

Examples:

IF CONSTAT% THEN \GOSUB 100 REM PROCESS OPERATOR INTERRUPT

WHILE NOT CONSTAT% \WEND

5.14 CONCHAR% Pre-defined Function

CONCHAR%

CONCHAR% reads one character from the console device.The value returned is an integer. The lower eight bits ofthe returned value are the binary representation of theASCII character input. The high-order eight bits arezero.

39

Page 47: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

Examples:

1% = CONCHAR%

CHAR% = "

IF' CONSTAT% THEN \CHAR% = CONCHAR%

IF CHAR% = STOPCHAR% THEN \RETURN

40

Input/Output Statements

Page 48: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Machine Language Linkage

6. MACHINE LANGUAGE LINKAGE STATEMENTS AND FUNCTIONS

6.1 PEEK Predefined Function

PEEK «expression»

The PEEK function returns the contents of the memorylocation given by the expression. The value returned isan integer ranging from 0 to 255. The memory locationmust be within the address space of the computer beingused for the results to be meaningful.

The expression must be numeric. An error occurs if astring expression is specified. Real values are roundedto the nearest integer.

Examples:

100 MEMORY%=PEEK(l)

FOR INDEX% = 1 TO PEEK%(BUFFER%)IN. BUFFER$ (INDEX%) = CHR$(PEEK%(BUFFER%+INDEX%»

NEXT INDEX%

6.2 POKE Statement

[<S~~ nwnber~j:Jl>~J<E <e

The low-order eight bits of the the second expressionare stored at the memory address selected by the firstexpression. The first expression must evaluate to a validaddress for the computer being used for the results to bemeaningful.

Both expressions must be numeric. An error occurs ifa string expression is specified. Real values are roundedto the nearest integer.

41

Page 49: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Versicm 2

Examples:

750 POKE l700,ASC("$")

f1achine Language Linkage

E'OR LOC% = 1 TO LEN (OUT. MSG$ )POKE MSG.LOC%+LOC%, ASC(MID$(OUT.MSG$,LOC%,l»

NEXT LOC%

6.3 CAI.L Statement

Tlle CALL statement is used t.O link to a machinelanguage subroutine. The expression is the address of thesubrolltine being referenced. This value must be withinthe address space of the computer being used.

Control is returned to the CBASIC program by executinga 8080 RET instruction. The hardware registers may bealtered by the subroutine, and, with the exception of thestack--pointer, they need not b4~ restored prior toreturning.

The expression must be numeric. An error occurs if astring expression is used. Real values are rounded to thenearest integer.

Examples:

CALL 5H

2000 CALL ANALOG.INPUT%

WHILE PEEK(PARAMETER%) <> 1CALL GET.RESPONSE%

WENDRETURN

Arguments may be passed to machine languagesubroutines with the POKE and PEEK instructions.

6.4 SAVEMEM Statement

r .~s~t ·n~;J:'~i'

The SAVEMEM statement reserves space for a machinelanguage subroutine, and loads the specified file duringexecution. Only one SAVEMEM statement may appear in aprogram.

42

Page 50: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Machine Language Linkage

ThE! constant must be an unsigned integer whichspecifi.es the number of bytes of space to reserve formachine language subroutines. The space is reserved inthe topmost (highest) address space of the CP/M transientprogram area. The beginning address of the reserved areais calculated by taking the constant specified in theSAVEMEr-1 statement and subtracting it from the 16 bitaddress stored by CP/M at absolute address 6 and 7.

The expression must be of type string and may specifyany valid unambiguous file name. The selected file isloaded into memory starting with the address calculatedabove. Records are read from the file until either an endof file is encountered or the next record to be read wouldover-write a location above the transient program area.

If the constant specifies less than 128 bytes to besaved, nothing will be read in, but the space will stillbe reserved. If the expression is a null string, space issaved but no file is loaded.

If a main program has a SAVEMEM statement, any chainedprogram that has a SAVEMEM statement must reserve the same.amount of space. Each chained program may load a newmachine language file, or it may use the file loaded by aprevious program. The space reserved by the main programmay not. be reclaimed by a subsequent program.

It is the programmers responsibility to insure thatthe machine language routines are assembled to execute atthe proper address. In addition, it should be noted thatthe location at which a program is loaded is dependentupon the size of the CP/M system being used.

Examples:

SAVEMEM 256, "SEARCH. COM"

SAVEMEM 512, DR$+ "CHECK." + ASSY$ (FN.CPM.SIZE%)

6.5 Use of Integers

Although all the machine language linkage statementswill accept either real or integer values where anexpression is required, it is much more efficient to useinteger quantities. The size of the INT file will bereduced, and the program will execute faster.

43

Page 51: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Machine Language Linkage

Since the largest positive CBASIC integer is 32767,the use of integer variables to address the upper 32K ofmemory requires that the desired address be converted to ~./

an appropriate negative number. Remember that in 2'scomplement representation of binary numbers a -1 is 16lis. This is most easily overcome by expressingaddresses as either hexidecimal or binary constants. Forinstanc:::e, if a programmer desires to call an assemblylanguage program at 48000 decimal, the followinginstruc:::tion will accomplish this:

CALL 0C000H

44

Page 52: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

7.

CBASIC Version 2

PREDEFINED FUNCTIONS

Predefined Functions

This chapter describes predefined functions provided byCBASIC. Predefined functions are used to build expressions asexplained in section 3.5. When a predefined function hasarguments, the arguments may be any valid expression whichevaluates t,o the correct type, either numeric or string.

In general, when a numeric expression is required, real andinteger arguments may be used interchangeably. However,efficiency is improved by using expressions as arguments thatdo not require conversion. In the definitions below, stringarguments are represented by A$, B$, etc, integers by 1%, J%etc, and real values by X, Y, etc.

Some predefined functions are discussed in chapters 5 and6.

7.1 Numeric Functions

The following functions return numeric values.Arguments, when required, may be any expression thatevaluates to either a floating point or integer number.

FRE

FRE returns the number of bytes of unused spacein the free storage area. The value returned is afloating point number.

X=FRE

IF FRE < 500.0 THEN GOSUB 10 REM PRINT WARNING

ABS(X)

ABS returns a value that is the absolute value ofthe argument X. If X is greater than or equal tozero the returned value is X, otherwise the returnedvalue is -X.

The value returned by ABS is a floating pointnumber. If X is a string an error occurs. If X isan integer, it is first converted to a floating pointnumber.

DISTANCE = ABS(START-FINISH)

IF ABS(DELTA.X) <= LIM THE:N STOP

45

Page 53: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

INT(X)

Predefined Functions

INT returns the integer part of the argument X.The fractional part is truncat:ed.

The value returned is a floating point number.If X is a string expression, an error occurs. If Xis an integer, it is first converted to a realvalue.

TIME=INT(MINUTES)+INT(SECONDS)

IF (X/2)-INT(X/2)=0 THEN PRINT \II EVEN II ELSE PRINT "ODD"

INT%(X)

INT% converts the argument X to an integer value.If X is a string, an error will occur. If X is aninteger, it is first converted to a real value, andthen it is converted back to an integer.

J% = INT%(REC.NO)

WIDTH% = DIMEN.l% + INT%(DIMEN.2)

FLOAT(I%)

FLOAT converts the argument 1% to a real value.If 1% is a string, an error ()ccurs. If 1% is real, ,,~../it is first converted to an int:eger, and then it isconverted back to a real number.

AMOUNT = FLOAT(COST%)

POSITION = SIN(FLOAT(ANG%) * OFFSET

RND

RND generatesnumber between 0real number.

a uniformly distributed randomand 1. ,]~he value returned is a

To avoid identicalea.ch time a programstatement must be usedgenerator.

46

sequencE~s ofis executed,to seE~d the

random numbersthe RANDOMIZErandom number

Page 54: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

DIE%=INT%(RND*6.)+1

IF RND > .5 THEN \HEADS% = TRUE% \

ELSE \TAILS% = TRUE%

SGN(X)

Predefined Functions

SGN returns an integer value that represents thealg'ebraic sign of the argument. It will return -1 ifX is negative, ~ if X is zero, and +1 if X is greatertha.n zero.

X may be either integer or real. Integer valuesof X are converted to real numbers. If X is astring, an error occurs. SGN always returns anint.eger.

IF SGN(BALANCE) <> ~ THEN \OUTSTANDINGBAL% = TRUE%

IF SGN(BALANCE) = -1 THEN \OVERDRAWN% = TRUE%

ATN(X)

ATN returns the arctangent of X. Using simpleide!ntities, other inverse trigonometric functions maybe computed from the arctangent. The argument isexpressed in radians.

The value returned is real. If X is an integer,it is first converted to a real number.

X = ATN(RADIANS)

TEMPERATURE = K + N(L%)/ATN(X)

ASIN = ATN(X/(SQR(l.-X*X»)

ACOS = PI/2. - ATN(X/SQR(l-X*X»

47

Page 55: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

COS (X)

Predefined Functions

COS returns the cosine of X. The argument X isexpressed in radians. /

.......",

The value returned is real. If X is an integer,it is first converted to a real value.

IF COS(ANGLE) = e.e THEN VERTICAL% = TRUE%

PRINT CONSTANT * COS(ROTA~rION)

EXP(X)

EXP returns the value of the irrational constant"E!" raised to the power given by X.

The value returned is real,. If X is an integer,it~ is first converted to a real number.

Y = A * EXP(BX%)

LOG (X)

E=EXP(l) REM CONSTANT E = 2.7182 •••••

The natural or Naperian l09arithm of the argumentX is returned by LOG.

The value returned is real.. If X is an integer,it. is first converted to a real number.

BASE.TEN.LOG = LOG(X)/LOG(le)

PRINT "LOG OF X IS II: LOG (X)

SIN(X)

SIN returns the sine of thE! X. The argument isexpressed in radians.

The value returned is real.. If X is an integer,it. is first converted to a real number.

FACTOR(Z) = SIN(A - B/C)

IF SIN (ANGLE/ (2.0 * PI» -- 0.0 THEN \PRINT "HORIZONTAL"

48

Page 56: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

SQR(X)

Predefined Functions

SQR returns the square root of the X. If Xnegative, a warning message is printed, andsquare root of the absolute value of the argumentreturned.

istheis

7.2

The value returned is real. If X is an integer,it is first converted to a real number.

HYPOT = SQR«SIDEl~2.0)+(SIDE2~2.0»

PRINT USING \liTHE SQR ROOT OF X IS: ####.##": SQR(X)

TAN(X)

TAN returns the tangent of the argument X. X isexpressed in radians.

The value returned is real. If X is an integer,it is first converted to a real number.

POWER. FACTOR = TAN(PHASE.ANGLE)

QUIRK = TAN(X - 3.0 * COS(Y»

Strinog Functions

ASC(A$)

ASC returns the ASCIIof the first characterthe length of A$ is zeroerror will occur.

numeric value (in decimal)of the string argument. If(null string), a runtime

The value returned is an integer.argument is numeric, an error will occur.

If the

IF ASC(DIGIT$»47 AND ASC(DIGIT$)<58 THEN \PRINT "VALID DIGIT"

OUT TAPE.PORT%, ASC("*")

49

Page 57: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

CHR$ (1%;)

Predefined Functions

CHR$ returns a one charactE!r striI;}g consisting oftl1le character whose ASCI I equivalent is 1%. CHR$ ....../can be used to send control characters to an outputde!vice. For instance, the stat.ement "PRINT CHR$(10)1Iwill output a line feed to the console.

The value returned is a string. If 1% is real,it is first converted to an integer value.

IF CHR$(INP(IN.PORT%» = IIA M THEN GOSUB 100

PRINT CHR$ (BELL%) REM ring the bell!

LEFT$ (1l.$, 1%)

LEFT$ returns a string consisting of the first 1%characters of A$. If 1% is greater than the lengthof A$, the entire string will be returned. If 1% iszero, a null string will be returned; if 1% isnegative, a runtime error will occur.

A$ must be a string; othE!rwise an error willoccur. 1% should be numeric. If 1% is real, it willfirst be converted to an integE!r. If 1% is a string,an error will occur.

PRINT LEFT$ (INPUT. DATA$, 2~j)

IF LEFT$(IN$,l) = lIyll THEN GOSUB 400

LEN(A$)

LEN returns the length of A$. Zero is returnedif A$ is a null string.

The value returned by LEN is an integer. Anerror occurs if the argument is numeric.

IF LEN(TEMPORARY$) > 25 THEN \TOO.LONG% = TRUE%

FOR INDEX% = 1 TO LEN(OBJECT$)NUM%(INDEX%) = ASC(MID$(OBJECT$,INDEX%,l»

NEXT INDEX%

50

Page 58: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

UCASE$ (A.$ )

Predefined Functions

UCASE$ returns a string in which the lower casecharacters in A$ have been translated to uppercase.Other characters are not altered. A$ remainsunchanged unless A$ is set equal to UCASE$(A$).

The value returned by UCASE$ is a string. Anerror occurs if A$ is numeric.

IF UCASE$(ANS$) = "YES" THEN \RETURN \

ELSE STOP

NAME$ = UCASE$(NAME$)

MATCH(A$,B$,I%)

MATCH returns the positionoccurrence of A$ in B$ startingposition given by 1%. A zero willmatch is found. The followingfeatures are available:

of the firstwith the characterbe returned if nopattern matching

1) A pound sign (#) will match any digit(0-9).

2) An exclamation mark (1) will match anyupper or lower case letter.

3) A question mark (?) will match anycharacter.

4) A backslash (\) character serves as anescape character to indicate the characterthat follows does not have special meaning.For instance a question mark signifies thatany character is a match unless preceeded bya backslash.

A$ and B$ must be strings. An error will occurif either of these arguments are numeric. If 1% isreal, it will first be converted to an integer: if 1%is a string, an error will occur. If 1% is negativeor zero, a runtime error will occur. When 1% isgreater than the length of B$, zero is returned. IfB$ is a null string a 0 is always returned. If B$ isnot null but A$ is null a 1 will be returned.

51

Page 59: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

Examples:

Predefined Functions

MATCH("is","Now is the",l) returns 5

MATCH(" ##I,"0c tober 8, 1976",1) returns 12

MATCH("a?I,l character",4) returns 5

MATCH("\#","123#4S",1) ret.urns 4

MATCH ( "ABCD", "ABC II , 1) returns 0

Note that the third examplE~ returns a 5 insteadof a 3 because the starting position for the match isposition 4. In example four the backslash causes thepound sign to match only another pound sign.without the backslash a 1 would be returned.

The next example is a more complicated statementusing the backslash:

MATCH("\#1\\\?I,"1tl\?2t",1) returns 2

The following program may l,e used to experimentwith the match function.

TRUE% = -1FALSE% = 0edit$ = " The number of oc<::urrences is ##t II

WHILE TRUE%INPUT "enter object s1:ring" : LINE object$INPUT " enter argument string" LINE arg$GOSUB 620PRINT USING edit$; occurrence%

WEND

620 rem-----count occurrences---------­location% = 1occurrence% = 0WHILE TRUE%

location% = MATCH(arg$,object$,location%)IF location% = 0 THEN RETURNoccurrence% = occurrence% + 1location% = location% + 1

WENDEND

52

Page 60: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

MID$(A$,I%,J%)

Predefined Functions

MID$ returns a string consisting of the J%chclracters of A$ starting at the 1% character. If 1%is greater than the length of A$, a null string isret:urned. If J% is greater than the length of A$,all the characters from 1% to the end of A$ areret:urned. An error occurs if either 1% or J% isnegative. A runtime error also occurs if 1% is zero.A zero value of J% will return a null string.

A$ must be a string expression; otherwise anerror will occur. 1% and J% must be numeric. If 1%or J% are real, they will first be converted toint~egers; if either 1% or J% are strings, an errorwill occur.

DIGIT$ = MID$(OBJECT$,POS%,l)

DAY$ = MID$("MONTUEWEDTHUFRISATSUN",DAY%*3-2,3)

RIGHT$ (Jl.$, 1%)

RIGHT$ returns a string consisting of the 1%rightmost characters of A$. If 1% is negative, aruntime error occurs; if 1% is greater than thelength of A$, the entire string is returned. If 1%is zero, a null string is returned.

A$ must evaluate to a string; otherwise an errorwill occur. 1% must be numeric. If 1% is real, itwill first be converted to an integer; if 1% is astring, an error will occur.

IF RIGHT$(ACCOUNT.NO$,l) = "0" THEN \TITLE.ACCT% = TRUE%

NAME$ = RIGHT$(NAME$,LEN(NAME$)-LEN(FIRST.NAME$»

STR$(X)

STR$ returns therepresents the value of

characterthe number X.

string which

If X is a string, an error will occur. If X isan integer, it will be converted to a real value.

PRINT STR$(NUMBER)

IF LEN(STR$(VALUE»>5 THEN ED$="#######"

53

Page 61: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

VAL(A$ )

Predefined Functions

VAL converts A$ into a floating point number.Conversion continues until a character is -...../encountered that is not part of a valid number oruntil the end of the string is encountered.

If A$ is a null stringcharacter of A$ is notre~turned.

or thea +, -

first non-blankor digit, zero is

The nameincluded inaddition, ifword TRACEwill not becommands arefile:

A$ must be a string: otherwise an error willoc:cur.

PRINT ARRAY$ (VAL ( IN. STRING$ ) )

ON VAL(PROG.SEL$) GOSUB H~, 20, 30,40, 50

COMMAND$

COMMAND$ returns a string 'vhich contains the CP/Mcommand line modified as described below. Refer toDigital Research publication "CP/M Interface Guide"for a discussion of the Command Line.

of the program bl:!ing executed is notthe string returned by COMMAND$. In

the TRACE option is used with CRUN, theand associated line numbers, if present,

included. If any of the followingused to execute a CBASIC intermediate

CRUN2 PAYROLL NOCHECKS TO~rALS

CRUN2 PAYROLL TRACE NOCHECKS TOTALS

the COMMAND $ function will return the followingst:ring:

NOCHECKS TOTALS

LE~ading blankscharacters willAll alphabeticcase.

are removed. A maximum of 50be retained by the COMMAND$ function.characters are converted to upper

The COMMAND$ function may be used at anytime in aprogram, as many times as desired, and by any programwhich is subsequently loaded by a CHAIN Statement.

54

Page 62: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

SADD(A$)

Predefined Functions

toth4~

Th4~

SADD returns the address of the string assignedthe argument A$. The first byte is the length ofstring followed by the characters in the string.length is stored as an unsigned binary integer.

Therefore, if the string isfunction would return thecontaining a binary 5. The nextASCII IIT II etc.

IITOTAL II , the SADDaddress of a bytebyte would be an

The value returned by SAnD is an integer. If A$is not a string, an error occurs. When the parameterevaluates to a null string, a zero may be returned.

The SAnD function, in conjunction with PEEK andPOKE, may be used to pass a string to an assemblylanguage routine for processing.

The following statements will put the address ofSTRING$ into the address stored in PARM.LOC%:

POKE PARM.LOC%,SADD(STRING$) AND 0FFHPOKE PARM.LOC%+l,SADD(STRING$)/256

VARPTR «variable»

VARPTR returns the permanent storage locationassigned to the <variable> by the run-time monitor.

In the case of an unsubscripted numeric quantity,this is the actual location of the variable inquestion. For string variables, the value returnedis the address of a sixteen-bit pointer to there:Eerenced string. Because strings are dynamicallyallocated the actual location of the string may vary,but the value returned by VARPTR remains unchangedduring execution of a program. If the variable is incommon, then the location returned by VARPTR willremain unchanged after chaining.

If the <variable> is subscripted, the valueret.urned by VARPTR is the address of a pointer to thearray dope vector in the free storage area. Thearray follows the dope vector. The first byte of thedope vector is the number of dimensions. Followingthis single byte are n-l (n is the number ofdimensions) 16 bit offsets into the arrray. Thefinal 16 bit quantity in the dope vector is thenumber of entries in the array. The array follows inrow major order.

55

Page 63: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

7.3 Disk Functions

RENAME(A$,B$)

Predefined Functions

RENAME is a function that changesfile specified by B$ to the nameRenaming a file to a name thatproduces a runtime error.

the name of thegiven by A$.

already exists

The RENAME predefined function returns an integervalue. A true (-1) is returned if the rename issuccessful and a false (0) is returned in cases wherethe rename fails. For instance false is returned ifB$ does not exist.

A file must be closed before it is renamed;otherwise, when CBASIC automatically closes files atthe end of processing, it will attempt to close therenamed file under the name with which it was opened.This will cause a runtime error because the originalfile name will no longer exist in the CP/M filedirectory.

Both arguments must be of type string. If eitherA$ or B$ is numeric an error will occur.

The RENAME function will allpw a CBASICprogrammer to use the following backUp convention:

1. The output file is opened with a filetypeof 1$$$1 indicating that it is temporary.

2. Any file with the same name as the outputfile but with a type IBAK I is deleted.

3. Data is written to the temporary file asthe program does its processing.

56

Page 64: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Predefined Functions

4. At the end of proces;sing, the programrenames any file with the s;ame filename andfiletype as the output file to the same

'-.j filename but with the filet~ype I BAK I •

5. The program renames thE! temporary outputfile to the proper name and type.

Examples:

DUMMY% = RENAME(lIpAYROLL.MST II ,lIpAYROLL.$$$")

IF RENAME (NEWFILE$, OLDFILE~:) THEN RETURN

SIZE(A$)

SIZE returns the size in blocks of the filespecified by A$. If the file is empty or does notexist, zero is returned. A~: may be any CP/Mambiguous file name. Digital Research publicationIIAn Introduction to CP/M Features and Facilities ll

explains ambiguous file names.

The argument must be anumeric value will resultfunction returns an integer.

Examples:

SI ZE ( IINAMES . BAK II )

string expression. Ain an error. The SIZE

SIZE(COMPANY$ + DEPT$ + II.NEW II )

SIZE(IIB:ST?RTR?K.*II}

SIZE(II*.*II)

SIZE(II*.BAS")

The SIZE function returns the number of blocks ofdiskette space consumed by the file or filesreferred to by the argument.. When the operatingsystem allocates diskette space to a file, it does soin one block increments. A file of 1 character willoccupy a full block of space.. This means the SIZEfunction returns the amount of space that has beenreserved by the file rather than the size of the datathat is in the file.

57

Page 65: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Predefined Functions

This function is useful in a program that mustduplicate or construct a file on disk. If theprogram knows that it will create a file of a givensize, possibly dependent on the size of its input~/file, it can first determine whether or not there issufficient free space on the disk before building thenew file. For example, consider a program whichreads a file named II INPUT II from drive A, processesthe data, and then writes a file named II OUTPUT II todrive B. Assume the size of 1I0UTPUT" will be 125% ofIIINPUT II • The following routine will insure thatspace is available on disk B prior to processing.

70 rem------test for enough room-----­size.of.output% = 1.25 * size(IIA:INPUT II )free.blocks% = 241 - size("B:*.*")if free.space% < size.of.output% then \

enough.room% = FALSE% \else enough.room% = TRUE%

return

CP/M supports 241 user accessible blocks onsingle density systems. The number of blocks in use,subtracted from 241, gives the remaining space on thedisk.

Note that some systems, such as those with doubledensity disk drives, may not provide resultsconsistent with standard disKs. CBASIC determinesthe number of blocks in a file by counting thenon-zero bytes in the file control block allocationmap.

58

Page 66: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

8. USER DEFINED FUNCTIONS

User Defined Functions

Functions or sUbprograms are defined by a programmer whenthe same computation is to be performed in a number oflocations within a program. The required routine is coded asa function and then referenced or called from any locationwithin the program. The function may be passed values orparameters to be used in each invocation.

All CBASIC functions return a value. Thus, the functionis, in effect, a reference to a routine which results in avalue, eithE~r string or numeric. CBASIC provides two types offunctions, single statement and multiple statement.

A function must be defined prior to any reference to thefunction. That is, the compiler must encounter the functiondefinition prior to any reference to the function.

8.1 Function Names

The name of a user defined function must begin with'FN' followed by any combination of numbers, letters andperiods.. A function name may be any length. Only thefirst 31 characters are considered when determining theuniqueness of a function name. No spaces are allowedbetween the FN and the remainder of the name.

The type of the function name determines the type ofthe value returned by the function. If the function nameends wi1:h a dollar sign, a string is returned: if the nameends in a percent sign, an integer is returned.Otherwise, a real value is returned. A function name isused to both define a function and to reference afunction.

Examples of function names:

FN .. THIS.IS.A.VALID.FUNCTION

FN:3.l4l6%

FN '. FUNCTION$

FN"TIMES

FN '. TRUNCATE $

59

Page 67: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

8.2 Function Definitions

User Defined Functions

Single statement functions are defined with the DEFstatement whose general form is:_/

[~stmt number>] DE!' <function name>( «dummy a.rg list»] = <expression>

The type of the expression must match the type of thefunction name. There may be none, or any number of dummyarguments, and they may be used freely within theexpression. A dummy argument is either a string ornumeric variable. When there is more than one argument,they are separated by commas. The type of the dummyarguments is independent of the function type.

The dummy arguments are local to the functiondefinition. Variables of the same name, in otherportions of the program, remain unaffected by the use ofthe function. Variables, constants, and other functionsmay also be referenced in the expression. Recursive callsare not permitted.

Examples:

DEF FN25 = RND*25.0

DEF FN.LEFT.JUSTIFY$(A$,LEN%)=LEFT$(A$+BLNKS$,LEN%)

DEF FN.HYPOT(SIDEI,SIDE2)= \SQR«SIDEI*SIDEI) + (SIDE2*SIDE2»

DEF FN.FUEL.USE(MILES)=SPEED*FN.CONST*MILES+OVERHEAD

DEF FN.EOJ%=FLAGI% OR FLAG2% OR FLAG3% OR FLAG4%

DEF FN.INPUT%(PORT%)=INP(PORT%) AND MASK%(PORT%)

A multiple statement function consists of a multiplestatement function definition, a function body and a FENDstatement. Multiple statement function definitions usethe following form of the DEF statement:

[I <stmt number> ] PEF <function name>( <dUJr(lJu;re.~9 Iis ~» ]

The dummy argument list is identical to that describedfor single statement functions. The parameters are localto the entire body of the function.

60

Page 68: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 User Defined Functions

The body of a multiple statement function consists ofany num:ber of CBASIC statements except that DEF and COMMONstatements may not appear in the body of, a function. Amultiple statement function may reference itself withinthe body of the function but, all local variables retaintheir most recent definition when returning from thefunction.

If a DIM statement appears in afunction, a new array is allocatedthe DIM statement. The previous datais lost. Note that the array isprogram.

multiple statementon each execution ofstored in the arrayglobal to the entire

A value is returned from a mUltiple statement functionby having the name of the function appear on the left handside of an assignment statement. Any number of suchassignments may appear in the body of a function. Themost recent assignment is the value returned by thefunction.

The function returns when a return statement isexecuted. Any number of return statements may be presentin the body of a multiple statement function. If noassignment is made to the function name, the valuereturned is the last value assigned to the function name.If no value has been assigned, zero is returned.

The body ofterminated by aFEND statement is:

a multiple statement function isFEND statement. The general form of an

q<stmt number>] FEND

Execution of a FEND statement implies that a multiplestatement function was exited without executing a RETURNstatement. In this case a runtime error occurs.

Examples:

DE1~ FN. READ. INPUT ( INPUT. NO% )READ # INPUT.NO%; CUSTNO%, AMOUNTRETURN

FEND

61

Page 69: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 User Defined Functions

DEF FN.COUNT%(INDEXl%)COUNT% = 0FOR 1% = 1 TO INDEXl%

COUNT% = COUNT% + ARI~Y(I%)

NEXT 1%FN.COUNT% = COUNT%RETURN

FEND

8.3 Function References

A user defined function may be referenced in anyexpression. The same number of parameters must bespecified in the call as are defined in the DEF statement.Parameters may be any valid expression, but they mustmatch the type of those specifi.ed in the definition.This includes integer and real parameters. If thefunction definition requires an integer parameter, thevalue passed to the function must be an integer. The samerule applies to real and string parclmeters.

A function must be defined prior to a reference to thefunction.

Prior to calling the function, t~he current value ofeach expression is substituted for the dummy variable inthe definition.

Examples:

PRINT FN.A(FN.B(X»

IF FN.LEN%("INPUT DATA",X$,Q) < LIMIT% THENGOSUB 100

WHILE FN.ALTITUDE(CURR.ALT%) > MINIMUM.SAFECURR.ALT%=INP(ALT.PORT%)

WEND

62

,.../

Page 70: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Formatted Printing

\...../ 9. FORMATTED PRINTING

9.1 General

This chapter describes the PRINT USING statement.PRINT USING allows specification of printed output using aformat string. A format string is composed of data fieldsand literal data. Data fields may be numeric or string;any character in the format string that is not part of adata field is a literal character. The general form of aPRINT USING statement is:

[kstmt number>] PRINT USING <format string> :, [<file reference>] <expx:ession list>

A format string may be any string expression. This allowsthe format to be determined during program execution. Anerror occurs if the format string is numeric; a runtimeerror occurs if the expression evaluates to a nullstring.

The expression list consists of expressions separatedby commas or semicolons. The comma does not causeautomatic tabbing as it does with the unformatted print.Each expression in the list is matched with a data fieldin the format string. If there are more expressions thanfields in the format string, the format string is reusedstarting at the beginning of the string.

While searching the format string for a data field,the type of the next expression in the list, either stringor numeric, determines what data field is used. Forinstance, if while outputting a string a numeric datafield is encountered, the characters that make up thenumeric data field will be treated as literal data. Ifthere is no data field within the format string of thetype required, an error will occur.

A PRINT USING statement without the file referencecauses an output line to be written to either the consoleor the line printer. The console is selected unless anLPRINTER statement is in effect. If the file reference ispresent, the line is composed as it 'would be if the outputwas being printed on a list device. The entire line isthen written as a record in the selected file. Chapter10 discusses in more detail the use of PRINT USING withdisk files.

63

Page 71: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

9.2 String Character Field

Formatted Printing

A one character string data field is specified withan exclamation point. The firs1: character of the next.~./

express.ion in the print statement list is output. Forexample::

&"; F.NAME$"M.NAME$,L.NAM$

F.NAME$ = "Lynn" :"Kobi"PRINT USING "1. 1.

would output:

L. M. Kobi

M.NAME$ = "Marion" L.NAM$ =

In this example, the period is trea1:ed as literal data.Since there are two expressions in the list, the formatstring is reused when processing thE! second expression.

9.3 Fixed Length String Fields

A fixed length string data field of more than oneposition is specified by a pair of slashes (I) separatedby zero or more characters. The width of the field isequal to the number of characters between the slashes,plus two. Any character may bE! placed between theslashes; these fill characters are ignored.

A string expression from the print list is leftjustified in the fixed field, and, if necessary, padded onthe right with blanks. A string, which is longer than thedata field, is truncated on the right. For example:

FORl$ = "THE PART REQUIRED IS / ••• 5 •••• 0 •••• 5/"PA.RT.DESCRP$ = "GLOBE VALVE, ANGLE"PRINT USING FORl$; PART .DESCRP~;

will output:

THE PART REQUIRED IS GLOBE VALVE, ANG

The use of the periods and numbE!rS between the slashesmakes it easy to verify that the data field is 16characters long. They have have no effect on the output.

9.4 Variable Length String Fields

A variable length string field is specified with anampersand (&). This results in a string being outputexactly as it is defined.

64

Page 72: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

For example:

Formatted Printing

COMPANY$ = "SMITH INC."PRINT USING "& &"; "THIS REPORT IS FOR",COMPANY$

will output:

THIS REPORT IS FOR SMITH INC.

A string may be right justified within a fixed fieldusing the variable string field. The following routineshows how this would be done:

IIFLD"S% = 212'BLK~? = II

PHONE$ = "213-355-112'63"PRINT USING "#&"; RIGHT$(BLK$

which would output:

+ PHONE$, FLD.S%)

# 213-355-112'63

In the above example, since the print list contains only astring expression, the pound sign is used as a literalcharacter. A pound sign may also indicate a numeric datafield. This is explained in the next section.

9.5 Numeric Data Fields

'-./ A numeric data field is specified by a pound sign (#)to indicate each digit required in the resulting number.One decimal point may also be included in the field.Values are rounded to fit the data field. Leading zerosare replaced with blanks. When the number is negative, aminus sign is printed to the left of the most significantdigit. A single zero is printed on the left of thedecimal point if the number is less than 1 and a positionis provided in the data field. The following exampleillustrates the use of numeric data fields.

x = 123.7546Y = -21.12'FOR$ = "####.####PRINT USING FOR$;PRINT USING FOR$;

###.#X, X, XY, Y, Y

###"

Execution of the above program produces the followingprintout:

,

'-/

123.7546-21.12'12'12'12'

123.8-21.12'

124-21

65

Page 73: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Formatted Printing

Numbers may beappending one ornumeric data field.segment.:

printed inmore uparrows

For example,

~~xponential format by(A) to the end of the

t.he following program

x = 12.345PRINT USING "#.###AA

would output:

": X, -x

1.235E 01 -.123E 02

The exponent is adjusted so that all positions representedby the pound signs are used. For instance:

PRINT USING "###.##AAA": 17.987

results, in:l79.87E-0l

Four positions are reserved for thE! exponent regardlessof the number of uparrows used in the field.

If one or more commas appear embedded within a numericdata field, the number is printed with commas betweengroups of three digits before 1:he decimal point. Forexample::

PRINT USING "##,###

prints:

": 100, 1000, 10000

100 1,000 10,'17'17'17

Each comma which appears in the data field is includedin the width of the field. Thus, E!Ven though only onecomma is required to obtain embedded commas in the output,it is clearer to place commas in the data field in thepositions they will appear on the output. For instance,the following data fields will produce the same results,except that the width of the first field allows only 9digits to be output. Using the second field, 1'17 digitsmay be output.

#,#########

#,###,###,###

If the exponent option is used, commas are notprinted: when commas occur in the field, they are treatedas pound signs.

66

Page 74: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Formatted Printing

Asterisk fill of a numeric data field is accomplishedby appending two asterisks to thE~ beginning of the datafield. A floating dollar sign may be obtained byappending two dollar signs to 1:he field in a similarmanner. Exponential format may not be used with eitherasterisk fill or the floating dollar sign. The pair ofasterisks or dollar signs are included in the count ofdigit positions available for the field and they appear inthe output only if there is sufficient space for thenumber and the asterisk or dollar sign. The dollar signis suppressed if the value printed is negative. Forexample:

COST = 8742937.56PRINT USING "**##,######.##PRINT USING "$$##,######.##

prints:

": COST, -COST": COST, -COST

**8,742,937.56$8,742,937.56

A number may bethe leading sign ifis a minus sign.replaces the minusexample:

*-8,742,937.56-8,742,937.56

output with a trailing sign instead ofthe last character in the data field

When the numbE!r is positive, a blanksign in the printed result. For

PRINT USING "###- ###AAAA_ ": 10, 10, -10, -10

will output:

10 l00E-0l 10- l00E-0l-

If a minus sign is the first character in a numericdata field, the sign position is fixed as the next outputposition. When the number being printed is positive, ablank is output: otherwise a minufi sign is printed. Thefollowing example demonstrates this feature.

PRINT USING "-#####

which outputs:

": 10, -10

10 10

Any time a number will not fit ~dthin a numeric datafield without truncating digits before the decimal point,a percent sign is printed followed by the number in thestandard format.

67

Page 75: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

For inst.ance:

X =: 132.71PRINT USING "##.# ###.#"; X,X

will out~put:

% 132.71 132.7

9.6 Escape Characters

Formatted Printing

At t~imes it may be desired to include a character asliteral data which, following the above rules, would bepart of a data field. This can be accomplished by"escaping" the character. A backslash (\) preceding anycharacter causes the next character after the backslash tobe treat.ed as a literal character. This allows, forinstanCE!, a pound sign to precede a number as shown in thefollowing example.

I TE:M . NUMBER = 31PRINT USING "THE ITEM NUMBEI

68

Page 76: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Versicln 2

10. FILES

10.1 HOW CP/M Maintains Files

Files

CBASIC uses the CP/M file accessing routines to storeand retrieve data from diskette files. This section willprovide a brief introduct~on to the file organizationemployed by CP/M. More detailed information is availablein the CP/M manuals.

CP/M maintains a directory of File Control Blocks(FCB's) on each diskette. The FCB contains the file name,number 'of records in the file, and references to physicallocations occupied by the data on the diskette. CP/Minterfaces with the disk hardware through primitives thatare used by transient programs, including CBASIC, toaccess files on disk. The primitives allow a file to becreated, opened, closed, read or written. All data isprocessed in 128 byte segments. However, CBASIC maintainsall necessary pointers and buffers data so the user is notrestricted to 128 byte records. All CBASIC file accessesare performed using CP/M system calls.

The CBASIC statements used to access diskette fileswill n()w be discussed. Three statements are used toactivate a file, OPEN, CREATE, and FILE. Once a file hasbeen a1ctivated, READ and PRINT statements may access andwrite files respectively. An active file may bedeactivated with either a CLOSE or DELETE statement.Chapter 11 provides additional information on programmingwith files.

10.2 OPEN Statement

The OPEN statementreading or updating.statement is:

activates an existing file forThe general form of an OPEN

[<stm~ number>] OPEN <expression> [DeL <expression>]AS I,<expression> [BUFF <express.1on> Des <expression> ]

! {, <expression> [:REeL <expression>]AS i<expression> [BUFF <express.1<;>n> !mCS <expression>]}

69

Page 77: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

The first expression represents the name of a file ondiskette. The name may contain an optional drivereference. If the drive reference is not present, thecurrently logged drive is used. The file name must '-~,/conform to the CP/M format for unambiguous file names.Lower case letters used in file names are converted toupper case. The expression must be of type string; anerror occurs if it is numeric. The following examplesshow valid file names:

ACCOUNT.MSTCBASIC.COMB:INVENTOR.BAK

The third example shows a reference to a file on drive B.

The- directory on the selected drive is searched andthe named file is opened. If the file is not found in thedirectory, it is treated as if an end of file had beenencountered during a read. See the IF END statement forinformation on end of file processing. When a drivereference is present, it is the programmer'sresponsibility to insure such a drive is available on thesystem being used.

The AS expression assigns an identification number tothe file being opened. This value is used in futurereferences to the file. Each active file must have aunique number assigned to it. If the expression is not ,~J

between 1 and 20, a runtime error occurs. The expressionmust be numeric; real values are converted to integer. Astring value will cause an error.

Whe:n the optional RECL expression is present, thefile will consist of fixed length records. A runtimeerror occurs if the record length is negative or zero. Afile may be accessed randomly or sequentially when arecord length has been specified; otherwise onlysequent.ial access is allowed. The RECL expression must benumeric; real values are converted to integer. A stringvalue will cause an error.

The! BUFF and RECS expressions alee optional. If used,they both must be present. The expression following BUFFspecifies the number of disk sectors from the selectedfile to maintain in memory at one time. If the expressionis omitted, a value of one is assumed. The expressionfollowing RECS must be present when the BUFF expression isused, but the value of the expression is ignored. Forpossible future use, the value :should be the size of adisk SE!ctor. This is normally 128 bytes.

70

Page 78: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

\ ...........-/

If random access is to be used with a file, the BUFFexpression, if present, must evaluate to 1; otherwise aruntime error will occur.

Both expressions must be numeric; a string value willcause an error. Real values are converted to integers.

Twenty files may be active at one time. Buffer spacefor files is allocated dynamically. Therefore storagespace may be conserved by opening files as they arerequired and closing them when they are no longer needed.

Examples:

55!) OPEN "TRANS. FILII AS 9

OPEN FILE.NAME$ AS FILE.NO% BUFF 26 RECS 128

OPEN WORK.FILE.NAME$(CURRENT.FILE%) \RECL WORK.LENGTH% AS CURRENT.FILE% BUFF BS% RECS 128

Hi'J. 3 CLOSE Statement

The CLOSE statement deactivates an OPEN file; the fileis no longer available for input or output operations.The general form of a CLOSE statement is:

[<stm~ number> J CLOS~ <expre.ssioXl:> {, <expre.s.sion>}

Each expression refers to the identification numberof an active file. The file is closed, the file number isreleased, and all buffer space used by the file isdeallocated. Before the file may be referenced again itmust be reopened. An error will occur if the specifiedfile has not previously been activated with a CREATE, OPENor FILE statement.

If an IF END statement is currently associated withthe identification number for the file being closed, theIF END will no longer be in effect.

All active files are automatically closed when a STOPstatement is executed, or a control-Z is entered inresponse to an INPUT statement. Files are not closed if acontrol·-C is entered from the console, or if a runtimeerror o,ccurs.

Each expression must be numeric in the range 1 to 20.Real values are converted to integers. A string valuewill result in an error.

71

Page 79: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

Examples:

80~ CLOSE FILE.NO%

CLOSE NEW.MASTER.FILE%,OLD.MASTER.FILE%,UPDATE.812%

FOR X% = 1 TO NO. OF. WORl<. FILES%CLOSE X%

Nt~XT X%

CREATE Statement

ThE! CREATE statement is identical to an OPENstatement except that a new file is created on theselected drive. The general form of a CREATE statementis:

[<stmt number» CREATE <expreseio [RECI; <expression»AS <expression> [BUP:r <express )0 RECS<expression>]{, <expression> [REeL <express >]AS <expression> [BUJrJr <~xpression> RECS <expression>]}

When a file with the same name is present, theexisting file will be erased before the new file iscreated.

The! CREATE statement has no effect on any IF ENDstatement which is currently in effect for the "...,)identification number assigned to the new file.

Examples:

l2~~ CREATE "NEW.FIL" AS 19 BUFF 4 RECS 128

C~~ATE ACC.MASTER$ RECL M.REC.LEN% AS ACC.FILE.NO%

C~~ATE "B:"+NAME$+LEFT$(STR$(CURRENT.WORK%),3) \AS CURRENT.WORK%

1~.5 DELETE Statement

fromof a

filesform

referencedThe general

The DELETE statement removes thetheir respective directories.DELETE statement is:

[ <strnt number>] D.ELETE<expr~.siori> if I <expre.$sion>}

Each expression must be in the range of 1 to 2~. Ifthe number is not currently assigned to an active file, a

72

Page 80: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

runtime error occurs. The expressionReal values are converted to integer.result in an error.

Files

must be numeric.A string value will

If an IF END statement is currently associated withthe identification number for the file being deleted, theIF END will no longer be in effect.

Examples:

DEL:ETE 1

DEL:ETE FILE. NO%, OUTPUT. FILE. NO%

1% := 0WHILE 1% < NO.OF.WORKFILES%

1% = 1% + 1DELETE 1%

WEND

10.6 IF END Statement

When an end of file is detected on a file, one of twoactions will take place. If an IF END statement has beenexecuted for the file, control is transferred to thestatement labeled with the statement number following theTHEN. If no IF END statement has been executed, a runtimeerror occurs.

.,,--...

The IF END statement allows the programmeran end of file condition on an active file.form of "the IF END statement is:

t <St.mtrwnbeil;'>~>:t~: •

to processThe general

nwnber>

The IF END statement must be the only statement on aline; it may not follow a colon nor be part of a statementlist.

Any number of IF END statements may appear in aprogram for a given file. The most recently executed IFEND is the one that will be in effect. However, if aDELETE or CLOSE statement is executed, any IF ENDassociated with the identification number is no longereffective.

The expression must be numeric in the range 1 to 20.Real values are converted to integers. A string valuewill cause an error.

73

Page 81: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

When a condition exists which results in the transferof control to the statement associated with an IF ENDstatement, the stack is restored to the condition thatexisted prior to the statement which caused activation of ~/the IF END. Thus if the statement which resulted intransfer was in a subroutine, a return must be executedafter processing the end of file condition. Examples:

IF END # 7 THEN 500

IF END # FILE.NO% THEN 100.1

An IF END statement may be executed prior to assigningthe file number to a file. A subsequent OPEN on a filethat does not exist will cause execution to continue as ifan end of file had been encountered.

In the following example, if the file MASTER.DAT doesnot exist on drive B, control will be transferred tostatement 500.5. After a successful OPEN, an end of fileduring a read will cause execution to continue withstatement 500.

IF END tMASTER.FILE.NO% THEN 500.5OPEN "B:MASTER.DAT" AS MASTER.FILE.NO% BUFF 6 RECS128IF END # MASTER.FILE.NO% THEN 500

An IF END statement may also be used when writing to a '....,/file. In this case control is transferred to thestatement associated with the IF END when an attempt ismade to write to the file and there is no disk spaceavailable. Part of the record being created may have beenwritten to the file. When using fixed files, the lastrecord may be rewritten after additional space is freed.

FILE Statement

[<stmt number»FILE <variable> ((<expression»)I {, <variable> [«e:x:pression»]}

A F'ILE statement opens a file if it is present on thereferenced disk: otherwise a file with the specified nameis created. The variable contains the name of the file tobe accessed. As each file is activated, it is assignedthe next unused file number starting with 1. If all 20numbers are already assigned, an error occurs. If theexpression enclosed in parentheses is present, the valueof the! expression is the record length. The recordlength must be numeric. Real values are converted tointegers. A string value will cause an error.

74

Page 82: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

The variable must not be sUbscripted and it must be oftype string. It may not be a literal or an expression.

Examples:

FILE NAME$

FILE FILE.NAME$(REC.LEN%)

10.8 READ Statement

There are four forms of the READ statement whichaccess data from disk files. Each of the four statementswill be discussed in turn, and then some general commentsabout reading from disk files will be made. The first twotypes of the READ statement access files in a manneranalogous to using the INPUT statement to access datafrom the console. The last two forms are similar to theINPUT LINE statement.

The general form of the sequenti,al read is:

[<stmt number> J READ·. <expresslc,'lii> : <v$r.iable>{, <variable>}

The above READ statement reads sequentially from thefile specified by the first expression. The file will beread, field by field, into the variables, until everyvariablE~ has been assigned a value. Fields may beinteger, floating point, or string v,alues, and they aredelimited by commas.

numeric"value willrefer t:ooccurs.

The expression, which selects the file, must beReal values are converted to integer. A stringcause an error. In addition, the value mustan active file. Other1tlise, a runtime error

ExampleE; :

RElm t 7: STRING$ , NUMBER

RElm t FILE. MASTER%: NAME $ , ADDRESS$, CITY$, STATE$

The general form of the next variation of the READstatement is:

[<stmtl number» READ t <expressiop> , <expression> :: [<variable> (, <variable>})

75

Page 83: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

The second expression selects the record to be read. Arandom record specified by the second expression is readfrom the disk file specified by the first expression.The fields in the record are assigned to the variables in -/'the variable list. An error occurs if there are morevariables than fields in the record. To use this form ofthe read, the file must have been activated with the RECLoption specified.

The second expression must be numeric. If the valueis a string, an error will occur. Real values areconverted to integers. The record number may not be zero;if it is, a runtime error will occur. The expression istreated as a sixteen bit unsigned binary number. Thisallows record numbers in the range of 1 to 65,535.

A random read with no variables specified willposition the file to the selected record. A sUbsequentsequential read will access the selected record.

Example::

READ # FILE.NO%,REC.COUNT%; NAME$, PAY, HOURS,\TERM.OF.EMPLOY,SSN$

The following two forms of thefiles as lines of text. Thesequential variant is:

READ statement treatgeneral form of the

[<stmti number>] READ t <expressicl>Il>J LINE <variable>

This statement reads sequentially all data from thespecified file until a carriage return followed by a linefeed is encountered. All the data read up to, but notincluding, the carriage return and line feed is assignedto the single string variable specified in the READ LINEstatement. If the variable is not of type string, anerror occurs.

The random variant of the READ LINE has the followinggeneral form:

[<stmti number>] READ t <expression> , <expression> :LINE <variable>

The final variation of the READ statement reads therecord specified by the second expression from the filespecified by the first expression. The data is assigned tothe string variable as described for the previous form ofthe READ LINE statement.

76

Page 84: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

ThE! READ LINE statement permitsrecords containing ASCII data inline-by-line basis. For instance, anythe CP/M text editor could be read athe following example:

RE:AD , 12: LINE in.string$

Files

CBASIC to accessany format on a

file created withline at a time. In

HL9

all characters in the next record will be read until acarriage return followed by a line feed is encountered.

Additional examples follow:

READ" 12 : LINE NEXT.LINE.OF.TEXT$

READ #: INPUT.FILE%, RECORD%: LINE NEXT.ONE$

PRINT Statement

There are four variations of the~ PRINT statement whichoutput data onto disk files. Each of these will bediscussed in this section. Both sequential and randomfiles may be written using the following forms of thePRINT statement:

[<stm~ number>] PRINT t <expression>":<expression> (, <expression>}

[<stmt number>] PRINT # <expression> ,<expression> :<expression> (, <expression>}

The first form of the PRINT statement outputs thenext sequential record to the file specified by the firstexpression. Each of the expressions in the expressionlist will be written as a field separated by commas.String fields will be surrounded by quotation marks andthe las"t field will be followed by a carriage return and aline feed.

The expression following the pound sign must benumeric. A real value will be converted to an integer. Astring value will cause an error. In addition the valuemust refer to an active file: otherwise a runtime errorwill occur.

The second form of the PRINT statement outputs arandom record specified by the second expression to thedisk file specified by the first expression. The sameformat as described above is used. The file must havebeen 0pI:med with a fixed record length. An error occurs

77

Page 85: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

if there is insufficient space in the record for all thedata.

The second expression must be numeric. If the value~/is a string, an error will occur. Real values areconverted to integers. The record number may not be zero;if it is, a runtime error will occur. The expression istreated as a sixteen bit unsigned binary number. Thisallows record numbers in the range of 1 to 65,535.

Examples:

PRINT # 3; "JONES, BILL"

PRINT #FILE.NO%; NAME$, ADDR$, SALARY

PRINT #PAY%,EMPLNO%; EMPL.NM(EMPLNO%),HOURS(EMPLNO%)

PRINT # 1", 55; DATE

Both forms of the PRINT statement discussed aboveproduce files which may be read using the READ statementdiscussed in section 1".8. All values output to the fileare delimited with commas or a carriage return line feedpair. In addition all strings are enclosed in quotationmarks. If the data must be output in a specific format,such as when a report is being produced for laterprinting, the PRINT USING statement may be used with diskfiles. This type of the PRINT statement takes on the ",.,/following general forms:

[<stmt. number>] PRINT USING <expres$i.9n> ;# <expression> ; <expression> {, <expression>}

[<stm1j. number>] PRINT USING <ex:pr~s.si.pn> ;# <expression> , <exprfjl:.,sion> ;<expression> {, <expr$$$ion>}

These statements write data to files using theformatted printing options specified in the expressionfollowing the USING. Formatting options are described inChapter 9 and are the same as those for console output.The first form is for sequential access and the second isused with random access. Records are delimited with acarriage return followed by a line feed.

The expression following USING must be of type string.An error occurs if the expression is numeric. If thestring is a null string, a runtime error occurs. Theexpressions following the pound sign must follow the samerules as for unformatted printing to files.

78

Page 86: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

The PRINT USING statement with disk files gives theprogrammer the same extensive facilities for formattingdata that the USING clause permits when printing to theconsole or list device. Numbers may be formatted withcommas and decimal points: asterisks and dollar signs maybe floated. Records containing embedded quotation marksor commas may also be written to a disk file with thePRINT USING statement.

For example:

cents.wanted% = TRUE%editl$ = "$$##,###.##"edit2$ = "$$##,###"if cents.wanted% then \

edit$ = editl$ \else edit$ = edit2$

print using "The ""&"" costs" + edit$: \#file.no%: product$,price

If this procedure is executed, the result on file willbe:

ThE~ "X-RAY MACHINE" costs $91,327. 44crlf

The use of two adjacent quotation marks in the stringconstant. results in a single quotation mark being outputto the file.

10.10 AppEmding to a File

A file may be appended to by reading sequentiallyuntil t.he end-of-file is detected with IF END, and thenprinting additional records.

An example of appending to a file is shown below:

true% = -1if end # 3 then 200 rem process file not foundopen "master" as 3 buff fre/128 - 1 recs 128if end # 3 then 100 rem eof on process filewhile true%

read # 3: dummywend

100 print # 3: "this added to end"stop

200 print "file not found"stop

79

Page 87: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

This process may be made more efficien~ if the filewas built with the RECL option specified. The SIZEpredefined function is used to find the number of blocksin the file. The number of bytes in the file is _/calculated and then the number of records is determined.A random read is executed to this record and then the fileis read until an end of file is detected. The followingmultiple line function will perform this:

DEF FN.GET.TO.END%(FILE.NAME$,REC.SIZE%,FILE.NUM%)FN.GET.TO.END% = FALSE%FILE.SIZE% = SIZE(FILE.NAME$)IF FILE.SIZE% = 0 THEN \ REM FALSE IF NO FILE

RETURN \ELSE FN.GET.TO.END% = TRUE%IF END # FILE.NUM% THEN 100READ # FILE.NUM%,(FILE.SIZE% * l024)/REC.SIZE%WHILE TRUE%READ # FILE.NUM%: DUMMYWEND

100 RETURNFEND

Except for the case of adding to the end of a file,sequent.ial reading and printing should not be intermixed.

10.11 Re-'Initializing the Disk System

If it becomes necessary to change diskettes duringexecution of a CBASIC program, CP/M must be given anopportunity to re-initialize its internal diskette usagemap to accommodate the diskette being inserted. If thisis not done, valid data may be overwritten.

Diskettes should never be changed while any files areopen. If a file has been written to and not closed andthen an INITIALIZE statement is executed, all the new datacould be lost. This means that user programs must closeall active files before executing an INITIALIZE statement

The INITIALIZE statement will re-initialize the diskusage maps for all disks inserted into logged-in drives.The general form of the INITIALIZE statement is:

[<stmt number>] INITIALIZE

The drive selected prior to executing an INITIALIZEstatement remains selected after the initialization iscomplet,e.

80

Page 88: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Files

\.......,-/

Insure that diskette changes are complete prior toexecuting the INITIALIZE statement.

Examples,:

10 INITIALIZE

INITIALIZE

The INITIALIZE statement is equivalent to the CALL264 provided in version I of CBASIC.

81

Page 89: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

11. PROGRAMMING WITH FILES

11.1 File Facilities

Programming With Files

The facilities available to the CBASIC user foraccessing diskette files are extremely versatile,providing different file organizations and accessingmethods. The emphasis of this chapter will be on thepractical organization of files and the way in which theyare accessed.

11.2 File Organization

The organization of a file describes the way it isrepresented on the diskette. All data written to files byCBASIC is in character format using the ASCII code. Thecontents of both string and numeric variables are writtenas their representative ASCII characters, not as binarydata. This permits the use of both resident and transientCP/M commands with CBASIC data files.

Characters within CBASIC data files are organized as ahierarchy. The lowest level of the hierarchy is called afield. Groups of fields form records, and a file consistsof one or more records.

A field can contain either string or numeric data. Astring field is surrounded by quotation marks. A numericfield is never enclosed by quotes, and it may contain anyvalid number as described in Chapter 3. Fields areseparated from one another by either commas or a carriagereturn followed by a line feed.

CBASIC offers two file organizations, stream andfixed. These techniques are compatible to provide moreflexibility for the programmer.

82

Page 90: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

11.3 Stream Organization

Programming With Files

insert delimitersterminated by a

11.4

\"j When it is desired to store data sequentially, item byitem, stream organization is used. Accessing is performedon a strict field by field basis. There is no restrictionon the values or lengths of data that may be written; eachitem of data takes only as much room as needed for dataand delimiters. In other words there is no padding.

A portion of a stream file containing only stringfields may look like this:

Nfirst fieldN,"second field"crlf"third","U,"126.89"crlfNxxx123yyy"crlf

There are six fields in the above example. The fourthfield is a null string. The following example shows afile which contains both numeric and string data:

",John", 798642764, "California"crlf"Tom Jones", 1234.56, II Iowa"crlf

CB.ASIC will read files in which strings are notenclosed in quotation marks. In this case, commas serveas the delimiters. Therefore, no commas may be includedwithin the string, but a quotation mark embedded in thestring would be treated as a character in the string.Strings written to files by CBASIC will always beenclosed in quotes. An attempt to write a string thatcontains a quotation mark to a file will result in aruntime error.

The PRINT USING statement does notbetween fields; each record will becarriage return followed by a line feed.

Fixed Organization

Fixed organization ofstructuring of the dataapplication.

files providesthat pertains to

a logicala specific

A file is defined to be of fixed organization if therecord length option is used with the CREATE, OPEN, orFILE statements. Each individual item of data in fixedfiles is written as a single field delimited by a comma,

83

Page 91: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Programming With Files

as with stream organization, but with the added conceptof a fixed size record. A record is always delimited by acarriage return and a line feed.

One record is written each time any PRINT statement isexecuted. Each record always contains the number of bytesspecified by the RECL parameter regardless of the numberor size of the component fields. This implies that, whilea given field may be any length, the combined length ofall fields in the record must be less than the recordlength by at least two bytes to allow room for thecarriage return and line feed. The last field in a recordis not-followed by a comma.

For example:

CREATE file.name$ RECL 25 AS file.no%a$="one"b$="record one"c$="3"d$=""e$=lIfive"f$="abc123def"PRINT tfile.no%; a$,b$PRINT tfile.no%; c$,d$,e$PRINT tfile.no%; f$

produces the following file:

"one", "record one"" 3 " , II " , " five···' abc123def"

crlfcrlfcrlf

The record delimiters, carriage return and line feed(crlf), always occupy the last two bytes of the record andmust be included in the specified record length. In theabove example the linefeed is in the 25th position of eachrecord.. The space between the record delimiter and thelast valid field is padded with blanks.

A fixed file READ statement will always access a newrecord each time it is used. For example:

IF END tfile.no% THEN 100WHILE TRUE%

READ tfile.no%; field$PRINT field$

WEND1'210 STOP

84

Page 92: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Programming With Files

Uedng the data from the previousfollowing will be printed console:

one3a.bcl23def

example, the

The fixed organization of files implies awell-defined structure to the accessed data. Theprocessing program can decide the meaning of a givenfield by its relative position in a record, rather than bythe value of the data itself. This provides savings inprocessing time and programming effort.

Files that are organized as fixed provide fast andeasy access to the individual fields within each recordbecause all fields can be read in at one time. Fixedfiles may be reorganized by sorting on a key within eachrecord. In addition, fixed files permit random access asdescribed below.

Because CBASIC reads each record on a field by fieldbasis, it is recommended that each record on a given filecontain the same number of fields. If there is noinformation to fill a specific field in a record, either azero or null string should be written into the field.This will allow, for example, the fifth field of a salestransaction file to represent the amount of the sale, evenif some or all of the first four fields are not used in aparticular transaction.

S~netimes it is necessary to insure that a given fieldstarts at the same relative position within a record.Usually there will be some fields of fixed length and somefields of variable length. Numeric fields will alwaysfall into the latter category unless the range of numbersis restricted. String fields, however, can always be madeto be of fixed length by padding them with blanks.

For example:

string$ = left$(string$ + " ",2121)

This will always produce a field that is 2121 characters inlength,. By use of the STR$, function, numbers can beconvert.ed to strings and then padded, thus allowingunrestricted numeric data to be of fixed length.

85

Page 93: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Programming With Files

11.5 File Accessing Methods

An access method describes the order in which data isread from or written to a file. CBASIC supports two~)access methods, sequential and random. Either accessmethod may be used on files that are organized as fixed.Only sequential may be used on a stream organized file.

11.6 Sequential Access

In sequentially accessed files there is one field ofconcern, the "next" field. The program cannot backtrackor skip ahead, it must proceed one field at a time.

A procedure to sequentially access a file and write itto the console is shown below. The file contains thefollowing records:

"first field","second field","third"crlfMI,151,lxxx123yyy"crlf

The required statements are:OPEN file.name$ as file.no%WHILE TRUE%

READ #file.no%: field$PRINT field$

WEND

The output on the console would be:

first fieldsecond fieldthird

5xxx123yyy

The fourth line on the console is blank because thefirst field in the second record is a null string.

While reading data from a file sequentially, the READstatement will consider a field completed when itencounters either a comma or a carriage return. Withinthe quotation marks of a string field it is permissibleto have any character except a quotation mark.

When accessing a stream file, every field on the filewill be read once and none will be skipped. It ispossible to read in more than one field with a single readstatement.

86

Page 94: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

For example:

Programming With Files

WHILE TRUE%READ #file.no%i fielda$,fieldb$PRINT fielda$,fieldb$

WEND

would print the following on the console (using the filefrom the previous example):

first fieldthird5

second field

xxxl23yyy

The same field organization is used when writing astream file. Each variable specified in the PRINTstatement produces a single field in the file. When morethan one variable is output in a single PRINT statement,the corresponding fields will be delimited by commas.The last field written by each PRINT statement will bedelimited by a carriage return and line feed instead of acomma.

For example:

a$="number one"b$="two"c$="3"d$=""e$="five"f$="variable six"PRINT #file.no%i a$,b$PRINT #file.no%i c$PRINT #file.no%i d$,e$,f$

will put the following data in the file referenced byfile.no%:

"number one", "two"crlf"3"crlf"","five","variable six"crlf

On files that are read or written using the streamorgani,zation, it does not matter which field delimiter isused. The crlf assumes significance when accessing fileswith fixed organization or when using the READ LINEstatement described below.

87

Page 95: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Programming With Files

When using the CP/M TYPE command to display afile, the carriage return and line feed resultoutput. from each separate PRINT statement appearingsepara.te line.

CBASICin the

on a

11.7 Ra.ndom Access

In random access the program is not limited toaccessing the next record or field. Any record on thefile is as accessible as any other. Each record, orposition where a record may be placed, is referenced byits relative record number. Each record may containmultiple fields.

Randomly accessed files must use the fixedorganization. CBASIC locates each record on a randomlyaccessed file by taking the relative record numberspecified in the program, sUbtracting one from thenumber, and mUltiplying it by the length of a record. Theresult is the byte displacement of the record measuredfrom the beginning of the file. If the records were ofvarying length, the displacement could not be calculatedin this manner.

Normally random access files will be createdsequentially and then read or updated using random access.An example of this type of processing is an employee filefor a small business. If the business has twenty ".Jemployees, each would be assigned a number ranging from 1to 20. Each employee might have a record on file withfields containing their name, social security number, andrate of pay. The twenty records would be placed on thefile in employee number order using the sequential accessmethod with a fixed organization. Then, when anapplication program needed the data on employee number 12,a random read would be issued for relative record number12 and the proper data would be retrieved. The followingprogram would access the file described above:

TRUE% = -1OPEN lIemployee.mstll RECL 50 AS 3IF END # 3 THEN 500.1WHILE TRUE% rem loop until eof

INPUT t, enter employee number": employ. notREAD # 3, employ.no%: name$,ssn$,payPRINT USING II&'S pay rate is ###.##11: name$,pay

WEND500.1 STOP

88

Page 96: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Programming With Files

To summarize, the READ statement used with a streamorganized file will always access the next available fieldon the file regardless of the field length or which

~_ delimiter is used. In a fixed organization file, eachREAD statement will access the next record. A record isdelimited by a carriage return and a line feed. PRINTstatements function in a similar manner.

11.8 Special Features

The PRINT USING statement can be used to write data tofiles as well as to the console or printer. Its use andthe format of its output is the same when writing to afile as it is when writing to the console. If the file isfixed, the single field written by leach execution of thePRINT USING statement will be padded with blanks to thespecified record length. The PRINT USING is well suitedto text processing applications.

The following examples demonstrate the PRINT USINGstatement with files:

PRINT USING "&":#TEXT.FILE.NO:I..INE.OF.TEXT$

PRINT USING "SPEED=#####.### KPH": #OUT.FILE,TIME: \VELOCITY(TIME}

EDl$="&"ED2$=" $$,###.##"PRINT USING EDl$+ED2$+EDl$+ED2~~:#17,TRANS.NO: \

"PRINCIPAL:",PRIN,"INTEREST:",INTR

PRINT USING "&":#PRINTER.FILE:" n REM BLANK LINE

PRINT USING n/2345/":#WORK.FILE,REL.REC.NO:SORT.KEY$

IN$="X"WHILE IN$<>""

INPUT "ENTER DATA":LINE IN$PRINT USING "/ ••• 5 •..• 0 •••• 5 .••• 0 •• /": #4: IN$

WENDCLOSE #TEMP.FILE

The READ LINE statement allows a file to be accessedas though there was one field per record. Any commas orquotes will be read as part of the data. Only a carriagereturn and line feed will be treated as the delimiter.In effect there is no field structure in a file accessedwith the READ LINE.

89

Page 97: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Programming With Files

For example, if the following file exists:

"field oneil, "two", "3", 1111, "four"crlf"five"," s ix"crlf

and the following statements are executed:

READ #file.no%i LINE string$PRINT string$

the data printed on the console would be:

"field oneil, "two", "3", Mil, II four II

This should be compared with the following statements:

READ # file.no%i string$PRINT string$

which would output:

field one

All quotation marks and commas are considered part of thedata, but the data does not include either the carriagereturn or the line feed.

90

,..J

Page 98: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

12. COMPILER DIRECTIVES

Compiler Directives

12.1 Directive Format

Directives are used to control the action of thecompiler. Except for the END statement, all directivesbegin with a percent sign. The percent sign must be incolumn one. There may not be a line number preceding thepercent sign.

If characters on the same line following the directiveare not a part of the directive, they are ignored by thecompiler.

12.2 Listing Control Directives

%LIST

%NOLIST

%PAGE <constant>

%EJECT

The %LIST and %NOLIST directives allow listing onlyselected portions of a program while it is being compiled.The listing control directives may be placed anywhere in asource program and may be used as many times as desired.

%LIST sets toggle Bresets toggle B. Inprinter is controlleddirectives.

(chapteraddition,by the

13) on while %NOLISToutput to the disk and

%LIST and %NOLIST

The %PAGE directive sets the length of a page outputto the printer. The constant must be an unsigned integer.If it is negative or zero, an error occurs. Initially thepage length is set at 64.

As many %PAGE directives as desired may appear in aprogram. An error occurs if no constant is present.

The %EJECT directive positions 1:he listings directedto the printer and the disk to thE~ top of the next page.This is performed by outputting a fc)rmfeed character.

91

Page 99: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Compiler Directives

12.3 %INCLUDE

%INCLUDE <filename>

The %INCLUDE directive causes the compiler to compilethe file, specified in the include statement, into thesource immediately following the %INCLUDE directive. Thefile name may contain a drive reference, and must be oftype BAS. Included statements will be indicated inlistings with an equal sign (=) following the CBASICassigned statement number. Includes may be nested sixdeep, but they may not include themselves. For example:

%INCLUDE b:readin

J

will include the file READIN.BAS from drive B.

Since the files incorporated with %INCLUDE directivesare of type BAS they may be compiled separately. It iseasier to debug large programs if they are composed ofsmall, individually tested, routines.

The %INCLUDE directive allows the programmer to builda library of common routines. This reduces programmingtime. System standards, such as I/O port assignments, canbe put in included routines. If the programs are movedfrom one system to another, the include routine ischanged, and the programs recompiled. ,.J

Commonly used procedures, such as searches, validationroutines, or input routines, are candidates for includefiles. If many programs in a system access the same file,all file access commands, such as READ, PRINT, or OPEN canbe set up as separate include files. If the filedefinition needs to be changed, it can be made in onecommon file instead of several application programs. Itis particularly valuable to code these routines asmUltiple line functions.

It should be noted that a program segment may compilewithout errors when compiled separately, but when combinedwith other routines, compiler errors may occur. Theseerrors should be predictable and will usually result fromusing the same line number in more than one module.

92

Page 100: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Compiler Directives

12.4 %CHAIN Directive

%CHAIN <constant>, <constant>, <constant>, <constant>

The %CHAIN directive is used to set the size of themain program's constant, code, data, and variable areas.This is required when chaining to insure that a programchained will not overwrite a portion of the data areabeing passed by the previous program. The compiler forceseach of the four areas to be at least as large as therespective constant in the %CHAIN directive.

Each constant must be an unsigned positive integer.The first constant is the size of the area reserved forreal constants. The second constant is the size of thecode area. The third constant is the area used to storevalue from data statements. The final constant is thesize of the area used to store variables.

The constants may be expressed as hexadecimal numbersby appending the letter H to the number. If the area tobe reserved is greater then 32,767 the constant must bewritten as a hexadecimal number.

The values to use in the %CHAIN directive aredetermined by compiling each of the programs to be chainedtogether and using the largest value of each area. Thecompiler lists the size of each area at the end of acompilation. For instance, if three programs are to bechained and the CODE SIZE for the programs are 789, 1578,and 4917 bytes, the second constant in the %CHAINdirective would be 4917.

The %CHAIN directive is only required in the main orfirst program executed. For more information refer to thediscussion on the CHAIN statement.

12.5 END statement

[<stm~ number>] END,

An END statement indicates the end of the sourceprogram. It is optional and, if present, it terminatesreading of the source program. Any statements followingthe END statement are ignored.

An END statement may not begin with a percent sign.It need not begin in column one, but it must be the firststatement on the line.

93

Page 101: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Compiler Directives

A branch to an END statement is equivalent toexecuting a STOP statement.

Examples: -l500 END

END

...J

94

Page 102: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

13. OPERATIONAL CONSIDERATIONS

Operational Considerations

13.1 System Requirements

CBASIC operates with any CP/M based floppy disk systemhaving at least 24K bytes of memory. In order to make thebest use of the power and flexibility of CBASIC, a dualfloppy disk system and at least 48K of memory isrecommended. If CBASIC is executed in a system smallerthan 24K a CP/M LOAD ERROR may occur.

CBASIC will operate with CP/M version 2 and MP/Msystems. A special configuration of the runtime packageis available to take full advantage of the advancedfeatures of CP/M version 2 and MP/M.

13.2 CBASIC Compile-Time Toggles

Compiler toggles are a series of switches that can beset when compiling a program. The toggles are set bytyping a dollar-sign ($) followed by the letterdesignations of the desired toggles, starting one space ormore after the program name. Toggles may only be set forthe compiler.

Examples of the use of compiler toggles are:

CBAS2 ACCOUNT3 $BGF

B:CBAS2 A:COMPARE $GEC

CBAS2 PAYROLL $B

CBAS2 B:VALIDATE $E

Toggle B suppresses the listing of the program on theconsole during compilation.

If an error is detected, the error message is printedeven if toggle B is set. Toggle B does not affect listingto the printer (toggle F) or disk file (toggle G).

Initially toggle B is off.

Toggle C suppresses the generation of an INT file.Since the first compilation of a large program is likelyto have errors, this toggle will provide an initial

95

Page 103: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Versicm 2

syntax check withoutintermediate file.

Operational Considetations

the overhead of writing the

Toggle C is initially off. ",J

Toggle D suppresses translation of lower case lettersto upper case. For example, if toggle D is on, 'AMOUNT'will not refer to the same variable as 'amount'.

If toggle D is set, all keywords must be capitalized.

Initially toggle D is off.

T()ggle E is useful when debugging programs. If thistoggle is set, it will cause the runtime program toaccompany any error messages with the CBASIC line numberin which the error occurred. Toggle E will increase thesize of the resultant INT file, and therefore, should notbe used with debugged programs. Toggle E must be set inorder for the TRACE option (section 13.4) to be ineffect~.

Initially toggle E is off.

TOGGLE F will cause the compiled output listing to beprinted on the system list device, in addition to thesystem console. This provides a hardcopy of the compiledprogram. Even if the B toggle is set, a complete listingis provided if toggle F is set. Each page of the listinghas a title printed and the pages are numbered. Formfeedsare used to advance to the top of a page.

Initially toggle F is off.

Toggle G will cause the compiled output listing to bewritten to a disk file. The file containing the compiledlisting has the same name as the source file, and a typeof LST. If toggles G and B are specified, only errorswill be output at the console but a disk file of thecomplete program will be produced.

Normally the disk listing will be placed on the samedrive as the source file. The operator may select anotherdrive by specifying the desired drive, enclosed inparenthesis, following the G toggle as shown below:

CBAS2 B:TAX $G(A:)

Initially toggle G is off.

96

Page 104: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Operational Considerations

13.3 Compiler Output

CBASIC does not require that each statement of aprogram be assigned a statement number. The onlystatements that must be given a statement number are thosethat have control passed to them by the GOTO, GOSUB, ON orIF statements. During compilation, CBASIC assigns asequential number to each line independent of thestatement number which may be used by the programmer. TheCBASIC assigned line number is the one referred to inerror messages (if toggle E is specified) and when usingthe TRACE option. The line number takes one of threeforms:

n: or n* or n=

where n is the number assigned. In most cases the colon(:) will follow the number. The equal sign (=) is printedwhen the statement has been read in from a disk file witha %INCLUDE directive. The asterisk (*) is used when thestatement contains a user assigned statement number thatis not referenced anywhere in the program. For example:

1:2:3* H'4:5:

print II start II

name$=IFRED"gosub 40stop

rem print name

6:%include printrtn7= 40 rem-----rtn8= print name$9= return

10: END

rem rtn to printto print-----------

In the example, statement 3 has an asterisk becausethe 110 1 is not referenced at any place in the program.This can be useful during debugging or to help understandlarge programs written in other dialects of BASIC. Whenall unreferenced line numbers are removed, it is easier tosee the logic of the program ..

When an error is detected, the compiler prints a twoletter error code, the line number the error occurredin and the position of the error relative to the beginningof the source line. The position assumes tab charactershave been expanded.

97

Page 105: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Operational Considerations

13.4 TRACE

CRUN2<filename> [TRACE [<lnl> [,<ln2>JJJ

The TRACE option is used for run-time debugging. Itwill print the line number of each statement as it isexecuted. The output is directed to the console even whena LPRINTER statement is in effect. The line numberprinted is the number assigned to each statement by thecompiler. Consider the following program:

AMOUNT = 12.13TIME = 45.0PRINT TIME * AMOUNT

If the above program was compilE!d using the followingcommand:

CBAS2 TEST $E

and then executed with the trace option:

CRUN2 TEST TRACE 1,3

the following output would be produced:

AT LINE 0001AT LINE 0002AT LINE 0003

545.85

The TRACE option functions only if the toggle E hasbeen set on during compilation of the program.

The first number «lnl» is used to specify the linenumber where the trace is to l)egin. The second number«ln2» specifies where the trace is to stop. If no linenumbers are included in the command, the entire program istraced; if only the first line number is present, tracingstarts at this line number and continues for all linenumbers greater than the first nwnber <lnl>.

13.5 Cross Reference Lister

In addition to CBAS2.COM and CRUN2.COM, a utilityprogram XREF.COM is supplied "dth version 2 of CBASIC.XREF produces a disk file which contains an alphabetizedlist of all identifiers used in a CBASIC program. The

98

.J

Page 106: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Operational Considerations

usage of the identifier (function, parameter, or global)is provided, as well as a list of each line in which thatidentifier is used. The listing places all functionsfirst with parameters and local variables associated witha function immediately following the function. Thefunctions are in alphabetical order. The output isnormally directed to the same disk as the source file.The file created has the same name as the CBASIC sourcefile and is of type XRF. The standard output is 132columns wide. The following command is used to invokeXREF:

XREF <filename> [disk ref] [$<toggles>] ['<title>']

The filename must be a CBASIC source program with afiletype of BAS. The disk reference is optional andspecifies the disk on which to place the cross referencefile. If the disk reference is not present, the listingis placed on the same drive as the source. It isspecified as A:, B: etc. For example:

XREF PAYROLL A:

will put the cross reference listing for PAYROLL. BAS ondrive A. At least one blank must separate the filenameand the disk reference.

Toggles may be used to alter the standard output ofXREF. At least one blank must separate the dollar signfrom the portion of the command line to the left. Thetoggles follow the dollar sign. They may be either loweror upper case letters. A, B, C, D, E, F, and G are validtoggles. Any other characters following the dollar sign,and before the title field or end of the command line, areignored.

The A toggle causes a listing to be output to the listdevice as well as to a disk file.

The B toggle suppresses output to the disk. If onlythe B toggle is specified, no output is produced.

The C toggle suppresses the output to the disk andpermits output to the list device. The C toggle has thesame effect as specifying both the A and B toggles.

The D toggle causes the output to be produced eightycolumns wide instead of using 132 columns.

99

Page 107: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Operational Considerations

andwhenuser

The E toggle produces output with only the identifiersand their usage. No line numbers are printed. The Etoggle might be used to help document a program. Theprogrammer would write the use of each identifier on thelisting provided by XREF. Also the file created by XREFcould be edited and made into a large remark with commentspertaining to each variable name. By including this filewith the source program, additional documentation would beprovided.

The F toggle allows the user to change the defaultpage length of 60 lines per page. The desired number oflines per page is enclosed in parenthesis and must followthe F. There may be no imbedded blanks. Formfeedcharacters are used to position the printer and are alsoplaced in disk files.

The G toggle suppresses printing of the heading linessuppresses all formfeeds. This toggle might be usedbuilding a disk file which will then be printed by autility.

The H toggle suppresses translationletters to upper case. This allowsprograms compiled with compiler toggle D.

The following command: XREF GL $CD

of lower caseusing XREF with

.produces a cross reference listing on the list device. ,..."IThe listing is 80 columns wide.

XREF ACCT$REC B: $EAF(40)

createsdevicenumberslines.

a disk file on drive B and a listing on the listof all the identifiers and their usage. No linewould be provided. Pages are limited to 40

The optional title field must be the last field in thecommand line. All characters following the firstapostrophe on the command line up to the secondapostrophe, or until the end of the command line, becomethe title. The title is printed on the heading line ofeach page of output. The title is truncated to thirtycharacters if the listing is 132 columns wide and totwenty characters if the D toggle is specified. Thefollowing command demonstrates the use of the titlefield:

XREF NAMES B: $AD 'version 2: 1 AUG 78'

100

Page 108: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

APPENDIX A

Compiler Errors

NO SOURCE FILE: <filename>.BAS

Compiler Error Messages

The compiler could not locate a source file on thespecified disk. This file was used in either the CBAS2command or a %INCLUDE directive.

OUT OF DISK SPACE

The compiler has run out of disk space whileattempting to write either the INT file or the LST file.

OUT OF DIRECTORY SPACE

The compiler has run out of directory entries whileattempting to create or extend either the INT file or theLST file.

DISK ERROR

A disk error occurred while trying to read or wr i te toa disk file. This message may vary slightly in formdepending on the operating system being used. See yourCP/M documentation for the exact meaning of this message.

PROGRAM CONTAINS n UNMATCHED FOR STATEMENT(S)

There are n FOR statements for which a NEXT could notbe found.

PROGRAM CONTAINS n UNMATCHED WHILE STATEMENT(S)

There are n WHILE statements for which a WEND couldnot be found.

PROGRAM CONTAINS I UNMATCHED DEF STATEMENT

A :multiple line function was not terminatedFEND statement. This may cause other errorsprogram.

101

with ain the

Page 109: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

WARNING INVALID CHARACTER IGNORED

Compiler Error Messages

Th.e previous line contained an invalid character.character is ignored by the compiler. A question markprinted in its place.

INCLUDE NESTING TOO DEEP NEAR LINE n

Theis

An include statement near line n in the source programexceeds the maximum level of nesting of include files.

Other errors detected during compilation cause a 2 lettererror code to be printed with the line number and position ofthe error. The error message normally follows the line inwhich the error occurred.

The possible error codes are:

BFA branch into a multiple line function from outside

the function was attempted.

BNAn invalid numeric constant was encountered.

CFCommon statement must be in the first line.

CIAn invalid file name was detected in a %INCLUDE

direct.ive. The file name may not contain a ?, *, or :(except as part of a disk reference where a colon may bethe second character of the name).

CSA COMMON statment, which was not the first statement

in a program, was detected. Only a compiler directivesuch as %CHAIN, a REMARK statement, or blank lines mayproceed a COMMON statement.

CVAn improper definition of a subscripted variable in a

common statement. Possibly the subscript count is not aconstant or there is more than one constant. Only oneconstant may appear in parenthesis. It specifies thenumber of subscripts in the array being defined.

102

Page 110: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

DL

Compiler Error Messages

The same line number was used on two different lines.Other compiler errors may cause a DL error message to beprinted even if duplicate line numbers do not exist.Errors such as not defining functions prior to use and, insome cases, if the DIM statement does not proceed allreferences to an array, a DL error will result.

statement wasin another DIM

leftthat

mayof

DP

FA

A variable dimensioned by a DIMpreviously defined. It either appearsstatement or was used as a simple variable.

A function name appears on theassignment statement but is not withinother words, the only function name thatleft of an equal sign is the namecurrently being compiled.

side of anfunction. Inappear to thethe function

FD

FE

FI

FN

FP

FU

IE

The same function name is used in a second DEFstatement.

A mixed mode expression exists in a FOR statementwhich the compiler can not correct. Probably theexpression following the TO is of a different type thanthe index.

An expression which is a subscripted numeric variableis being used as a FOR loop index.

A function reference contains an incorrect number ofparameters.

A function reference parameter type does not match theparameter type used in the function's DEF statement.

A function has been referenced before it has beendefined, or the function was never defined.

An expression used immediately following an IFevaluates to type string. Only type numeric ispermitted.

103

Page 111: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

IF

Compiler Error Messages

A variable used in a FILE statement is of type numericwhere type string is required.

IPAn input prompt string was not surrounded by quotes.

ISA sUbscripted variable was referenced before it was

dimensioned.

ITAn invalid compiler directive was encountered. A

parameter required by the directive may be out of range ormissing. Or the directive may be misspelled.

IUA variable defined as an array in a DEF statement is

used without subscripts.

MC

MF

The same variable isCOMMON statement. EachCOMMON statement.

defined more than once in avariable may only appear in one

MM

MS

ND

A.n expression evaluates to type string when anexpression of type numeric is required.

An invalid mixed mode has been detected. Most likelyvariables of type string and type numeric are combined inthe same expression.

A numeric expression was used where a stringexpression is required.

A FEND statement was encountered without acorresponding DEF statement. This error could be theresult of an improper DEF statement.

NIA variable referenced by a NEXT

match the variable referenced bystatement.

statement does notthe associated FOR

NUA NEXT statement occurs without an associated FOR

statement.

104

Page 112: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

OF

Compiler Error Messages

A branch out of a multiple line function from insidethe function was attempted.

00

PM

More than 40CBASIC has ansingle program.causes problems.

ON statements were used in the program.arbitrary limit of 40 ON statements in a

Notify Digital Research if this limit

RF

SD

SE

SF

SN

SO

TO

A DEF statement appeared within a multiple linefunction. Functions may not be nested.

A multiple line function may not call itself.

A second SAVEMEM statement was encountered. A programmay have only one SAVEMEM statement.

The source line contained a syntax error. This meansthat a statement is not properly formed or a keyword ismisspelled.

A SAVEMEM statement uses an expression of type numericto specify the file to be loaded. The expression must bea string. Possibly the quotation marks were left off astring constant.

A subscripted variable contains an incorrect number ofsubscripts, or a variable in a DIM statement has been usedpreviously with a different number of dimensions.

The statement is too complex to compile. It should besimplified. Consider making the expression into two ormore expressions. Please send Digital Research a copy ofthe source statement.

Symbol table overflow has occurred. This means thatthe program is too large for the system being used. Theprogram must be simplified or the amount of availablememory increased. Smaller variable names reduces theamount of symbol table space used. Digital Research isinterested in being informed if programs generate thiserror.

105

Page 113: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

UL

Compiler Error Messages

A line number that doesreferenced.

us

not exist has been

A string has been terminated by a carriage returnrather than by quotes.

vavariable names are too long for one statement. This

should not normally occurl If it does, please send a copyof the source statement to Digital Research. Reducing thelength of variable names and reducing the complexity ofthe expression within the statement may eliminate theerror.

WEThe expression immediately following a WHILE statement

is not numeric.

WNWHILE statements are nested to a depth greater than

12. CBASIC has an arbitrary limit of 12 for nesting ofWHILE statements.

WUA WEND statement occurred without an associated WHILE

statement.

106

Page 114: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

APPENDIX B

Run-Time Errors

NO INTERMEDIATE FILE

Runtime Error Messages

A file name was not specified with the CRUN2 command,or no file of type INT with the specified file name wasfound em the disk specified.

IMPROPER INPUT - REENTER

This message occurs when the fields entered from theconsole do not match the fields specified in the INPUTstatement. This can occur when field types do not matchor the number of fields entered is different from thenumber of fields specified. Following this message allvalues required by the input statement must be reentered.

Other errors detected cause a 2 letter code to be printed.If the code is preceded by the word WARNING, executioncontinues. If the code is preceded by the word ERROR,execution terminates. If an error occurs with a codeconsisting of an asterisk followed by a letter such as '*R'the runtime package has failed. .Please notify DigitalResearch of the circumstance under which the error occurred.

The possible codes are listed below:

Warning Codes

DZA number was divided by zero. The result is set to

the largest valid CBASIC number.

FLA field length greater than 255 bytes was encountered

during a READ LINE. The first 255 characters of the recordare retained; the other characters are ignored.

LNThe argument given in the LOG function was zero or

negative. The value of the argument is returned.

107

Page 115: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

NE

Runtime Error Messages ]A negative number was specified before the raise to a

power operator (A). The absolute value of the parameter isused in the calculation. When using real variables apositive number may be raised to a negative power, but anegative number may not be raised to a power.

OFA calculation using real variables produced an

overflow. The result is set to the largest valid CBASICreal number. Overflow is not detected with integerarithmetic.

SQA negative number was specified in the SQR function.

The absolute value is used.

Error Codes

ACThe string argument in an ASC function evaluated to a

null string.

AEAn attempt was made to access an array element before

the array DIM statement had been executed.

BN ..J

r

I

CC

The value following the BUFF option in an OPENCREATE statement is less than I or greater then 52.

or

CD

CE

CF

A chained program's code area is larger than the mainprogram's code area. Use a %CHAIN directive in the mainprogram to adjust the size of the code area.

A chained program's data area is larger than the mainprogram's data area. Use a %CHAIN directive in the mainprogram to adjust the size of the data area.

The file being closed could not be found in thedirectory. This could occur if the file name had beenchanged with the RENAME function.

A chained program's constant area is larger than themain program's constant area. Use a %CHAIN directive inthe main program to adjust the size of the constant area.

108

..J

Page 116: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

CP

Runtime Error Messages

A chained program's variable storage area is largerthan the main program's variable storage area. Use a%CHAIN directive in the main progJram to adjust the size ofthe variable storage area.

CSA chained program reserved a different amount of

memory with a SAVEMEM statement than the main program.

CUA CLOSE statement specified a file number that was not

active.

DFAn OPEN or CREATE was specified with a file number

that was already active.

DUA DELETE statement specified' Cl file number that was

not active.

DWAn error occurred while writing to a file for which no

IF END Statement has been executed. This may occur wheneither the directory or the disk i.s full.

EFA read past the end of file occurred on a file for

which no IF END statement had beerl executed.

ERAn attempt was made to writ:e a record of length

greater than the maximum record size specified in theOPEN, CREATE or FILE statement for this file number.

FRAn attempt was made to rename a file to an existing

file name.

FUAn attempt was made to read or write to a file that

was not active.

IFA file name was invalid. ~(ost likely an invalid

character was found in the file name. A colon may neverappear imbedded in the name propel'. Question marks andasterisks may only appear in ambiguous file names. Thiserror will also result if the file name was a nullstring.

109

Page 117: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

IR

Runtime Error Messages

A record number of zero was specified.

IV ,~../

An attempt was made to execute an INT file created by

IX

a version I compiler. Torecompiled using the versionerror will also result fromfile which is empty.

use CRUN2 a program must be2 compiler, CBAS2. This

attempting to execute an INT

ME

MP

NC

NF

NM

NN

NS

OD

A FEND statement was encountered prior to executing aRETURN statement. All mUltiple line functions must exitwith a RETURN statement.

An error occurred while creating or extending a filebecause the disk directory was full.

The third parameter in a MATCH function was zero ornegative.

Source program contains a real constant outside therange of CBASIC real numbers.

The file number specified was less than I or greater ,~-J

than 20, or a file statement was executed when 20 fileswere already active.

There was insufficient memory to load the program.

An attempt was made to print a number with a PRINTUSING statement but there was not a numeric data field inthe USING string.

An attempt was made to print a string with a PRINTUSING statement but there was not a string field in theUSING string.

A READ statement was executed but there are no DATAstatements in the program, or all data items in all DATAstatements have already been read.

110

Page 118: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

OE

Runtime Error Messages

An attempt was made to OPEN a file that didn't existand for which no IF END statement had been executed priorto executing the OPEN statement.

01The expression specified

ON ••• GOTO statement evaluatedgreater than the number of linestatement.

in an ON ••• GOSUB or anto a number less than I ornumbers contained in the

OM

QE

RB

RE

RF

RG

RU

The program ran out of memory during execution. Spacemay be conserved by closing files when they are no longerneeded and by setting strings to a null string when theyare no longer required. Also by not using DATAstatements, but rather reading the constant informationfrom a file, space will be saved. Large arrays may bedimensioned with smaller subscripts when the array is nolonger required.

An attempt was made to PRINT a string containing aquotation ,mark to a file. Quotation marks can only bewritten to files when using the PRINT USING option of thePRINT statment.

Random ,access was attempted to a file activated withthe BUFF op"tion specifying more than one buffer.

An attempt was made to read past the end of a recordina fixed file.

A recursive function call was attempted: recursion isnot supported in CBASIC.

A RETURN occurred for which there was no GOSUB.

A random read or print was attempted to other than afixed file.

SBAn arr.:lY subscript

boundaries :for which thewas used which exceededarray was defined.

the

111

Page 119: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

SL

Runtime Error Messages

A concatenation operation resulted in a string of morethan 255 bytes.

soThe file specified in a SAVEMEM statement could not be

located on the referenced disk. The expression specifyingthe file name must include the type if one is present. Atype of COM is not forced.

SSThe second parameter of a MID$ function was zero or

negative, or the last parameter of a LEFT$, RIGHT$, orMID$ was negative.

TLA TAB statement contained a parameter less than I or

greater than the current line width.

UNA PRINT USING statement was executed with a null edit

string or an escape char (\) was the last character in anedit string.

WRAn attempt was made to write to a file after it had

been read, but before it had been read to the end of thefile.

112

Page 120: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

APPENDIX C

KEY WORDS

Key Words

ABS AND AS ASC ATNBUFF CALL CHAIN CHR$ CLOSECOMMAND$ COMMON CONCHAR% CONSOLE CONSTAT%COS CREATE DATA DEF DELETEDIM ELSE END EQ EXPFEND FILE FLOAT FOR FREGE GO GOSUB GOTO GTIF INITIALIZE INP INPUT INTINT% LE LEFT$ LEN LETLINE LOG LPRINTER LT MATCHMID$ NE NEXT NOT ONOPEN OR OUT PEEK POKEPOS PRINT RANDOMIZE READ RECLRECS REM REMARK RENAME RESTORERETURN RIGHT$ RND SADD SAVEMEM-/ SGN SIN SIZE SQR STEPSTOP STR$ SUB TAB TANTHEN TO UCASE$ USING VALVARPTR WEND WHILE WIDTH XOR

113

Page 121: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Decirnal-Ascii-Hex Table

,~JDECIMAL ASCII HEX DECIMAL ASCII HEX DECIMAL ASCII HEX

0 NUL 00 44 2C 88 X 581 SOH 01 45 2D 89 y 592 STX 02 46 . 2E 90 Z SA3 ETX 03 47 / 2F 91 [ 5B4 EOT 04 48 0 30 92 \ 5C5 ENQ 05 49 1 31 93 ] 5D6 ACK 06 50 2 32 94 5E7 BEL 07 51 3 33 95 - SF8 BS 08 52 4 34 96

,60

9 HT 09 53 5 35 97 a 6110 LF 0A 54 6 36 98 b 6211 VT 0B 55 7 37 99 c 6312 FF 0C 56 8 38 100 d 6413 CR 0D 57 9 39 101 e 6514 SO 0E 58 3A 102 f 6615 SI 0F 59 . 3B 103 9 67,16 DLE 10 60 < 3C 104 h 6817 DCl 11 61 = 3D 105 i 6918 DC2 12 62 > 3E 106 j 6A19 DC3 13 63 ? 3F 107 k 6B20 DC4 14 64 @ 40 108 1 6C21 NAK 15 65 A 41 109 rn 6D22 SYN 16 66 B 42 110 n 6E ,J23 ETB 17 67 C 43 111 0 6F24 CAN 18 68 D 44 112 P 7025 CR 19 69 E 45 113 q 7126 SUB lA 70 F 46 114 r 7227 ESC IB 71 G 47 115 s 7328 FS lC 72 H 48 116 t 7429 GS ID 73 I 49 117 u 7530 RS IE 74 J 4A 118 v 7631 US IF 75 K 4B 119 w 7732 SP 20 76 L 4C 120 x 7833 1 21 77 M 4D 121 Y 7934 I' 22 78 N 4E 122 z 7A35 # 23 79 0 4F 123 { 7B36 $ 24 80 P 50 124 I 7C37 % 25 81 Q 51 125 } 7D38 & 26 82 R 52 126 7E39 27 83 S 53 127 DEL 7F40 ( 28 84 T 5441 ) 29 85 U 5542 * 2A 86 V 5643 + 2B 87 W 57

114

Page 122: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Master Index

.........................., ...............................................................

....

451515

579

un107113114115

1471,72491747

.............

.........

ABS(X) FUNCTIONALGEBRAIC OPERATORSAND OPERATORANGLE BRACKETS ••••••APPENDING TO A FILEAPPENDIX AAPPENDIX BAPPENDIX CAPPENDIX DAPPENDIX EARRAY •••••AS STATEMENTASC(A$)ASSIGNEMENT STATEMENTSATN(X) FUNCTION •••••••

BINARY CONSTANTSBRACESBRACKETSBUFF STATEMENT

..... 1155

69,70

............................(XREF)

...........

42,44,8182

27,28,3650715428,299591

10197

83933HJ39

4211948

2957298

9

........

.......

......

.....

....

.......

CALL STATEMENTCBAS2CBASIC 1CHAIN STATEMENTCHR$(I%)CLOSE STATEMENT ••••••COMMAND$ •••••••COMMON STATEMENTCOMPILE TIME TOGGLESCOMPILER DIRECTIVESCOMPILER ERROR MESSAGESCOMPILER OUTPUT •••••COMPILIER ••••••CONCHAR% FUNCTIONCONSOLE STATEMENTCONSTANTS •••••••••CONSTAT% FUNCTIONCONTINUATION CHARACTERCONTINUING STATEMENTCONTROL STATEMENTSCOS (X) FUNCTIONCP/M DOCUMENTATIONCP/M LOAD ERRORCREATE STATEMENTCROSS REFERENCE LISTERCRUN2

115

Page 123: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Master Index

DATA STATEMENTDEF FUNCTIONDELETE STATEMENTDIM STATEMENT ••DISK FUNCTIONS ......

·...·............

3560725,13,14,29

56

154

316319192015

616974696983644613,5923636345605962

20,215,93

15101107

74810,15,17

.....·...

·..·..........

·..........

......................

.......

..............

..

·... ....

·..........·.........

·........

..... .....

· .

·..........

· .

...

....

STATEMENTSINPUT/OUTPUTFORMATTED PRINTING

....

..............

........................

STATEMENT ••••••CONTROL BLOCKS

ELSE STATEMENTEND STATEMENTEO OPERATOR ••••••••••••••ERROR CODES (COMPILIER)ERROR CODES (RUNTIME)EXECUTION OF CBASIC PROGRAMEXP(X) FUNCTION •.•••EXPRESSION •••••••••

GE OPERATORGENERAL INFORMATIONGENERAL INFORMATIONGENERAL INFORMATIONGO STATEMENTGOSUB STATEMENTGOTO STATEMENTSGT OPERATOR

FENDFILEFILE STATEMENT •••••FILES •••••••••••FILE MAINTENANCE BY CP/MFIXED FILE ORGANIZATIONFIXED LENGTH STRINGS ••••FLOAT(I%)FN FUNCTIONFOR STATEMENTFORMAT STRINGFORMATTED PRINTINGFRE FUNCTION ••••••FUNCTION DEFINITIONS •••••FUNCTION NAMES •••••FUNCTION REFERENCES ••••

HEXADECIMAL CONSTANTSHIERARCHY OF OPERATORS · . 11

15

IDENTIFICATION NUMBERSIDENTIFIERS ••..•.•••••IF END STATEMENTIF STATEMENT ••.••••••••••INITIALIZE STATEMENTINP FUNCTIONINPUT STATEMENT

· . ·........ 31271,72,735,20

803936

"J

116

Page 124: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2 Master Index

...............................

·..........

464611112143

1

1551215121173891481622,253215

1135

.....

·...

·.

·...

·...·.

·...

·......

....

·.

.....

·....·..

·.

.....

....

......

·...

·.·..

· .

·.

·.. ..

·..

·..·.

·..·...

.....·.. . .

· .·.

......

.....

........

...

FUNCTIONFUNCTIONCONSTANTS

KEY WORDS FOR CBASICKEYWORDS (CBASIC)

LE OPERATOR •••LEFT$(A$,I%)LEN(A$)LET STATEMENTLINE INPUT STATEMENT ••••••LISTING CONTROL DIRECTIVESLOG(X) FUNCTION ••••••LOGICAL OPERATORSLOOPS ••••••••••••LPRINTER STATEMENT ••LT OPERATOR •••••••

INT (X)INT%(X)INTEGERINTEGER NUMBERSINTEGERSINTRODUCTION

MATCH(A$,B$,I%)MASTER INDEX ·. .... ·... ·.MID$(A$,I%,J%) ·.MIXED MODE OPERATIONS .. ·.. ·....MULTIPLE STATEMENTS ·....NE OPERATOR ·......

,--" NEXT STATEMENT ·.. ..NOT OPERATOR ..... ·.NOTATION ... ·.. ... ...NUMBERS ...... ..... ·.. ·. ...NUMERIC DATA FIELDS

ON STATEMENT ·.......OPEN STATEMENT ·......... ·... ·.. ·.OPTIONAL TITLE FIELD (XREF) .....OR OPERATOROUT STATEMENT .... ·.

51115

5317

5

152515

5112165

2569

11211211538

·......

PEEK FUNCTIONPOKE STATEMENTPOS FUNCTIONPOWER OPERATORSPREDEFINED FUNCTIONSPRINT # STATEMENTPRINT STATEMENTPRINT USING 1PRINT USING #PRINT USING %

..

...

·..

· ................· .·.........

·.

4133,413415457731646567

117

Page 125: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Versicm 2 Master Index

65666468667863

3

......·....·...

....

....

......... ....

..........

.....

......

NUMBERS

....·.........·........·.........

·..,/\

&USINGUSINGUSINGUSINGUSINGUSING I STATEMENT

PRINT USING STATEMENTSPROGRAM IDENTIFICATION

PRINTPRINTPRINTPRINTPRINTPRINT

88277675351711,1771,728470,7215,16

66

5636195146

un

........·........·..... .

...

READREADREADREALREAL

RANDOM FILE ACCESS •••••••••••••RANDOMIZE STATEMENT ••••

I LINE STATEMENT ••••••••••I STATEMENT •••••••••••••••STATEMENTCONSTANTNUMBERS

RECL STATEMENTRECORD DEI.IMITERS ••••••RECS STATEMENTRELATIONAl. OPERATORSREM STATEMENT •••••REMARK •••••••RENAME(A$,B$)RESTORE STATEMENTRETURN STATEMENTRIGHT$(A$,I%)RND FUNCTION •.••••RUNTIME ERROR MESSAGES ••••••

SADD(A$)SAVMEM STATEMENT ••••••••SEPARATE STATEMENTSSEQUENTIAL FILE ACCESSSGN(X) FUNCTIONSIN(X) FUNCTIONSIZE(A$)SPECIAL FEATURES •••••••••••••••SQR(X) FUNCTIONSTATEMENT NUMBERS •••••••••••••••••••STATEMENTSSTEP STATEMENTSTOP STATEMENTSTR$(X)STREAM FILE ORGANIZATIONSTRING CHARACTER FIELDSTRING FUNCTIONSSTRINGS ••••••SUB STATEMENT •••••••••••••SUBSCRIPTED VARIABLESSYMBOLS ••••••••••••••••••SYSTEM REQUIREMENTS

554221864748578949

54

232653836449101912

595

,...J118

Page 126: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

CBASIC Version 2

TAB FUNCTION •••••••••••••TABLE (DECIMAL-ASCII-HEX)TAN(X} FUNCTIONTHEN STATEMENTTO STATEMENTTOGGLE A (XREF)TOGGLE B (COMPILE)TOGGLE B (XREF)TOGGLE C (COMPILE)TOGGLE C (XREF)TOGGLE D (COMPILE)TOGGLE D (XREF)TOGGLE E (COMPILE)TOGGLE E (XREF)TOGGLE F (COMPILE)TOGGLE F (XREF)TOGGLE G (COMPILE)TOGGLE G (XREF)TOGGLE H (XREF)TRACE OPTION (COMPILE)TRACE OPTION (CRUN2)

UCASE$(A$}USER DEFINED FUNCTIONSUSING STATEMENT •••••••

....

....

Master Index

34114

4920239995999599969996

10096

10096

100100

9698

515963,78,89

VAL(A$}VARIABLE LENGTHVARIABLESVARPTR •••••

WEND STATEMENTWHILE STATEMENTWIDTH STATEMENT

XOR OPERATORXREF.COM •••••

STRINGS ..

...

54641255

222232

1698

%CHAIN DIRECTIVE%EJECT%INCLUDE%LIST%NOLIST%PAGE

119

939192919191

Page 127: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

.....)

,/

Page 128: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized

Digital Research invites your comments regarding the CBASIC languageand the contents of this manual. Your views, favorable orunfavorable, aid us in improving our products. Remove this page fromthe manual and use the backside for your comments. Fold it along thedotted lines, stamp, seal and mail it to Digital Research. Weappreciate your consideration. All comments and suggestions becomethe property of Digital Research.

····

stamp ..· .·........

DIGITAL RESEARCH, INC.Post Office Box 579Pacific Grove, California

93950

-------------------------------

121

Page 129: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized
Page 130: DRI CBASIC 2 Language Reference CBASIC 2... · · • 95 · . . . 95 · • 97 · • . . 98 · 98 ... C. KEY WORDS 113 D. DECIMAL - ASCII ... All spE~cial characters and capitalized