RTR logo

R. T. RUSSELL

BBC BASIC (Z80) Manual



General Information

Introduction

Line numbers

Line numbers are optional in BBC BASIC. A line must be numbered if it is referenced by a GOTO, GOSUB or RESTORE statement but otherwise the line number may be omitted. It can also be useful to number lines when developing and debugging a program, since it makes it easier to EDIT lines and error messages may contain the number of the line in which the error occurs.

It is never necessary to use line numbers. Instead of GOSUB you should use named user-defined procedures or functions. In the case of RESTORE you can use the relative option of the statement. You can avoid GOTO by making use of structures like REPEAT ... UNTIL and WHILE ... ENDWHILE and using the techniques described under Program Flow Control.

The RENUMBER command can be used to add line numbers automatically. Permissible line numbers are in the range 1 to 65535.


Statement Separators

When it is necessary to write more than one statement on a line, the statements should be separated by a colon ':'. BBC BASIC (Z80) will tolerate the omission of the separator if this does not lead to ambiguity. It's safer to leave it in and the program is easier to read.

For example, the following will work.

10 FOR i=1 TO 5 PRINT i : NEXT


Expression Priority

Order of Evaluation

The various mathematical and logical operators have a priority order. The computer will evaluate an expression taking this priority order into account. Operators with the same priority will be evaluated from left to right. For example, in a line containing multiplication and subtraction, ALL the multiplications would be performed before any of the subtractions were carried out. The various operators are listed below in priority order.

variables  functions  ()  !  ?  &  unary+-  NOT
^
*  /  MOD  DIV
+  -
=  <>  <=  >=  >  < << >> >>>
AND
EOR  OR

Examples

The following are some examples of the way expression priority can be used. It often makes things easier for us humans to understand if you include the brackets whether the computer needs them or not.

IF A=2 AND B=3 THEN
IF ((A=2)AND(B=3))THEN

IF A=1 OR C=2 AND B=3 THEN
IF((A=1)OR((C=2)AND(B=3)))THEN

IF NOT(A=1 AND B=2) THEN
IF(NOT((A=1)AND(B=2)))THEN

N=A+B/C-D N=A+(B/C)-D
N=A/B+C/D N=(A/B)+(C/D)


Variables

Specification

Variable names may be of unlimited length and all characters are significant. Variable names must start with a letter or underscore, and can only contain the characters A..Z, a..z, 0..9, @, ` (CHR$96) and underscore; embedded keywords are allowed. Upper and lower case variables of the same name are different.

The following types of variable are allowed:

real numeric
A% integer numeric
A& byte numeric
A$ string

Numeric Variables

Real Variables

Real variables have a range of ±5.9E-39 to ±3.4E38 and numeric functions evaluate to 9 significant figure accuracy. Internally every real number is stored in 40 bits (5 bytes). The number is composed of a 4 byte mantissa and a single byte exponent. An explanation of how variables are stored is given at Annex D.

Integer Variables

Integer variables are stored in 32 bits and have a range of -2147483648 to +2147483647. It is not necessary to declare a variable as an integer for advantage to be taken of fast integer arithmetic. For example, FOR...NEXT loops execute at integer speed whether or not the control variable is an 'integer variable' (% type), so long as it has an integer value.

Byte variables

(BBC BASIC version 5 or later only)
Byte variables are stored in 8 bits and have a range of 0 to 255.

Static Variables

The variables A%..Z% are a special type of integer variable in that they are not cleared by the statements RUN, CHAIN and CLEAR. In addition A%, B%, C%, D%, E%, H% and L% have special uses in CALL and USR routines and P% and O% have a special meaning in the assembler (P% is the program counter and O% points to the code origin). The special variable @% controls numeric print formatting. The variables @%..Z% are called 'static', all other variables are called 'dynamic'.

Boolean Variables

Boolean variables can only take one of the two values TRUE or FALSE. Unfortunately, BBC BASIC does not have true boolean variables. However, it does allow numeric variables to be used for logical operations. The operands are converted to 4 byte integers (by truncation) before the logical operation is performed. For example:

PRINT NOT 1.5  
      -2
The argument, 1.5, is truncated to 1 and the logical inversion of this gives -2
PRINT NOT -1.5  
       0
The argument is truncated to -1 and the logical inversion of this gives 0

Two numeric functions, TRUE and FALSE, are provided. TRUE returns the value -1 and FALSE the value 0. These values allow the logical operators (NOT, AND, EOR and OR) to work properly. However, anything which is non-zero is considered to be TRUE. This can give rise to confusion, since +1 is considered to be TRUE and NOT(+1) is -2, which is also considered to be TRUE.

Numeric Accuracy

Numbers are stored in binary format. Integers and the mantissa of real numbers are stored in 32 bits. This gives a maximum accuracy of just over 9 decimal digits. It is possible to display up to 10 digits before switching to exponential (scientific) notation (PRINT and STR$). This is of little use when displaying real numbers because the accuracy of the last digit is suspect, but it does allow the full range of integers to be displayed. Numbers up to the maximum integer value may be entered as a decimal constant without any loss of accuracy. For instance, A%=2147483647 is equivalent to A%=&7FFFFFFF.

String Variables

String variables may contain up to 255 characters. An explanation of how variables are stored is given at the Annex entitled Format of Program and Variables in Memory.


Arrays

Arrays of integer, byte, real and string variables are allowed. All arrays must be dimensioned before use. Integers, reals and strings cannot be mixed in a multi-dimensional array; you have to use one array for each type of variable you need.

Array arithmetic

(BBC BASIC version 5 or later only)

A limited number of arithmetic and logical operations are available which operate on entire arrays rather than on single values. These are addition (+), subtraction (-), multiplication (*), division (/), logical OR, logical AND, logical exclusive-or (EOR), integer quotient (DIV), integer remainder (MOD) and the dot product (.). For example:

C%() = A%() * B%() + C%()
B() = A() - PI
A() = B() . C()
A() = B() * 2 / C() + 3 - A()
Array expressions are evaluated strictly left-to-right, so higher priority operators must come first and brackets cannot be used to override the order of execution:
C%() = C%() + B%() * A%() : REM not allowed
C%() = A%() * (B%() + C%()) : REM not allowed
All arrays must be DIMensioned before use, and (with the exception of the dot product) the number of elements in all the arrays within an expression must be the same; if not, the Type mismatch error will result. In the case of the dot product the rules are as follows: The SUM function returns the sum of all the elements of a numeric array, so the mean value can be found as follows (assuming a one-dimensional array):
mean = SUM(A()) / (DIM(A(),1) + 1)
SUM may also be used with string arrays, it concatenates all the elements to form a single string (with a maximum length of 255 characters); the SUMLEN function sums the lengths of all the elements:
whole$ = SUM(A$())
wholelen% = SUMLEN(A$())
The MOD function returns the modulus (square-root of the sum of the squares of all the elements) of a numeric array, so an array can be normalised as follows:
A() = A() / MOD(A())
MOD may also be used to calculate the RMS (Root Mean Square) value of a numeric array:
rms = MOD(array()) / SQR(DIM(array(),1) + 1)
Don't confuse this with the MOD operator, which returns the remainder after an integer division.

You can use the compound assignment operators with arrays (e.g. +=, −=,*= or /=) but there is an important restriction. If the array is an integer (or byte) array the expression on the right-hand-side of the operator is converted to an integer before the operation is carried out. So the statement:

A%() *= 2.5
will multiply all the elements of array A%() by 2, not by 2.5.

Initialising arrays

(BBC BASIC version 5 or later only)

You can initialise the individual elements of an array in exactly the same way as you would normal variables. However you can also initialise the contents of an entire array in one operation:

A%() = 1, 2, 3, 4, 5
B$() = "Alpha", "Beta", "Gamma", "Delta"
C() = PI
If there are fewer values supplied than the number of elements in the array, the remaining elements are unaffected. However in the special case of a single value being supplied, all the elements of the array are initialised to that value. So in the last example all the elements of C() will be initialised to PI. There must be enough free space on the stack to contain a copy of the array.


Program flow control

Introduction

Whenever BBC BASIC comes across a FOR, REPEAT, WHILE, GOSUB, FN or PROC statement, it needs to remember where it is in the program so that it can loop back or return there when it encounters a NEXT, UNTIL, ENDWHILE or RETURN statement or when it reaches the end of a function or procedure. These 'return addresses' tell BBC BASIC where it is in the structure of your program.

Every time BBC BASIC encounters a FOR, REPEAT, WHILE, GOSUB, FN or PROC statement it 'pushes' the return address onto a 'stack' and every time it encounters a NEXT, UNTIL, ENDWHILE or RETURN statement, or the end of a function or procedure, it 'pops' the latest return address off the stack and goes back there.

Apart from memory size, there is no limit to the level of nesting of FOR ... NEXT, REPEAT ... UNTIL, WHILE ... ENDWHILE and GOSUB ... RETURN operations. The untrappable error message 'No room' will be issued if all the stack space is used up.

Program structure limitations

The use of a common stack has one disadvantage (if it is a disadvantage) in that it forces strict adherence to proper program structure. It is not good practice to exit from a FOR ... NEXT loop without passing through the NEXT statement: it makes the program more difficult to understand and the FOR address is left on the stack. Similarly, the loop or return address is left on the stack if a REPEAT ... UNTIL loop or a GOSUB ... RETURN structure is incorrectly exited. This means that if you leave a FOR..NEXT loop without executing the NEXT statement, and then subsequently encounter, for example, an ENDWHILE statement, BBC BASIC will report an error (in this case a 'Not in a WHILE loop' error). The example below would result in the error message 'Not in a REPEAT loop at line 460'.
400 REPEAT
410   INPUT ' "What number should I stop at", num
420   FOR i=1 TO 100
430     PRINT i;
440     IF i=num THEN 460
450   NEXT i
460 UNTIL num=-1

Leaving program loops

There are a number of ways to leave a program loop which do not conflict with the need to write tidy program structures. These are discussed below.

REPEAT ... UNTIL loops

One way to overcome the problem of exiting a FOR ... NEXT loop is to restructure it as a REPEAT ... UNTIL loop. The example below performs the same function as the previous example, but exits the structure properly. It has the additional advantage of more clearly showing the conditions which will cause the loop to be terminated (and does not require line numbers):
REPEAT
  INPUT ' "What number should I stop at", num
  i=0
  REPEAT
    i=i+1
    PRINT i;
  UNTIL i=100 OR i=num
UNTIL num=-1

Changing the loop variable

Another way of forcing a premature exit from a FOR ... NEXT loop is to set the loop variable to a value equal to the limit value. Alternatively, you could set the loop variable to a value greater than the limit (assuming a positive step), but in this case the value on exit would be different depending on why the loop was terminated (in some circumstances, this might be an advantage). The example below uses this method to exit from the loop:
REPEAT
  INPUT ' "What number should I stop at", num
  FOR i=1 TO 100
    PRINT i;
    IF i=num THEN
      i=500
    ELSE
      REM More program here if necessary
    ENDIF
  NEXT
UNTIL num=-1

Using the EXIT statement

(BBC BASIC version 5 or later only)
You can use the EXIT FOR statement to achieve the same effect as the first example, without requiring a GOTO:
REPEAT
  INPUT ' "What number should I stop at", num
  FOR i=1 TO 100
    PRINT i;
    IF i=num THEN EXIT FOR
    REM More program here if necessary
  NEXT i
UNTIL num=-1

Moving the loop into a procedure

A radically different approach is to move the loop into a user-defined procedure or function. This allows you to jump out of the loop directly:
DEF PROCloop(num)
LOCAL i
FOR i=1 TO 100
  PRINT i;
  IF i=num THEN ENDPROC
  REM More program here if necessary
NEXT i
ENDPROC
If you needed to know whether the loop had been terminated prematurely you could return a different value:
DEF FNloop(num)
LOCAL i
FOR i=1 TO 100
  PRINT i;
  IF i=num THEN =TRUE
  REM More program here if necessary
NEXT i
=FALSE

Local arrays

Since local variables are also stored on the processor's stack, you cannot use a FOR ... NEXT loop to make an array LOCAL. For example, the following program will give the error message 'Not in a FN or PROC':
DEF PROC_error_demo
FOR i=0 TO 10
  LOCAL data(i)
NEXT
ENDPROC
(BBC BASIC version 5 or later only)
Fortunately BBC BASIC allows you to make an entire array 'local' as follows:
DEF PROC_error_demo
LOCAL data()
DIM data(10)
ENDPROC
Note the use of an opening and closing bracket with nothing in between.


Indirection

Introduction

Many versions of BASIC allow access to the computer's memory with the PEEK function and the POKE statement. Such access, which is limited to one byte at a time, is sufficient for setting and reading screen locations or 'flags', but it is difficult to use for building more complicated data structures. The indirection operators provided in BBC BASIC (Z80) enable you to read and write to memory in a far more flexible way. They provide a simple equivalent of PEEK and POKE, but they come into their own when used to pass data between CHAINed programs, build complicated data structures or for use with machine code programs.

There are four indirection operators:

NameSymbolPurpose No. of Bytes Affected
Query?Byte Indirection Operator1
Pling!Word Indirection Operator4
Pipe|Floating Point Indirection Operator5
Dollar$String Indirection Operator1 to 256

The ? operator

Byte Access

The query operator accesses individual bytes of memory. ?M means 'the contents of' memory location 'M'. The first two examples below write &23 to memory location &4FA2, the second two examples set 'number' to the contents of that memory location and the third two examples print the contents of that memory location.
     ?&4FA2=&23
or
     memory=&4FA2
     ?memory=&23
     number=?&4FA2
or
     memory=&4FA2
     number=?memory
     PRINT ?&4FA2
or
     memory=&4FA2
     PRINT ?memory
Thus, '?' provides a direct replacement for PEEK and POKE.
?A=B  is equivalent to  POKE A,B
B=?A  is equivalent to  B=PEEK(A)

Query as a Byte Variable

A byte variable, '?count' for instance, may be used as the control variable in a FOR...NEXT loop and only one byte of memory will be used.
DIM count% 0
FOR ?count%=0 TO 20
  - - -

  - - -
NEXT

The ! operator

The word indirection operator (!) works on 4 bytes (an integer word) of memory. Thus,
!M=&12345678
would load
&78 into address M
&56 into address M+1
&34 into address M+2
&12 into address M+3.
and
PRINT ~!M   (print !M in hex format)
would give
12345678

The | operator

(BBC BASIC version 5 or later only)
The pipe (|) indirection operator accesses a floating-point value, which occupies 5 bytes of memory. Thus,
|F% = PI
would load the floating-point representation of PI into addresses F% to F%+4,

The $ operator

The string indirection operator ($) writes a string followed by a carriage-return (&0D) into memory starting at the specified address. Do not confuse M$ with $M. The former is the familiar string variable whilst the latter means 'the string starting at memory location M'. For example,
$M="ABCDEF"
would load the ASCII characters A to F into addresses M to M+5 and &0D into address M+6, and
PRINT $M
would print
ABCDEF

Use as binary (dyadic) operators

All the examples so far have used only one operand with the byte and word indirection operators. Provided the left-hand operand is a variable (such as 'memory') and not a constant, '?' and '!' can also be used as binary operators. (In other words, they can be used with two operands.) For instance, M?3 means 'the contents of memory location M plus 3' and M!3 means 'the contents of the 4 bytes starting at M plus 3'. In the following example, the contents of memory location &4000 plus 5 (&4005) is first set to &50 and then printed.
memory=&4000
memory?5=&50
PRINT memory?5
Thus,
A?I=B  is equivalent to  POKE A+I,B
B=A?I  is equivalent to  B=PEEK(A+I)
The two examples below show how two operands can be used with the byte indirection operator (?) to examine the contents of memory. The first example displays the contents of 12 bytes of memory from location &4000. The second example displays the memory contents for a real numeric variable. (See the Annex entitled Format of Program and Variables in Memory.)
10 memory=&4000
20 FOR offset=0 TO 12
30   PRINT ~memory+offset, ~memory?offset
40 NEXT
Line 30 prints the memory address and the contents in hexadecimal format.
 10 NUMBER=0
 20 DIM A% -1
 30 REPEAT
 40   INPUT"NUMBER PLEASE "NUMBER
 50   PRINT "& ";
 60   FOR I%=2 TO 5
 70     NUM$=STR$~(A%?-I%)
 80     IF LEN(NUM$)=1 NUM$="0"+NUM$
 90     PRINT NUM$;" ";
100   NEXT
110   N%=A%?-1
120   NUM$=STR$~(N%)
130   IF LEN(NUM$)=1 NUM$="0"+NUM$
140   PRINT " & "+NUM$''
150 UNTIL NUMBER=0
See the Annex entitled Format of Program and Variables In Memory for an explanation of this program.

Power of Indirection Operators

Indirection operators can be used to create special data structures, and as such they are an extremely powerful feature. For example, a structure consisting of a 10 character string, an 8 bit number and a reference to a similar structure can be constructed.

If M is the address of the start of the structure then:

$M    is the string
M?11  is the 8 bit number
M!12  is the address of the related structure
Linked lists and tree structures can easily be created and manipulated in memory using this facility.

The ^ operator

(BBC BASIC version 5 or later only)
You can discover the memory address at which a variable is stored using the 'address of' operator ^. Once you know its address you can access the value of a variable by means of the appropriate indirection operator:
A% = 1234
PRINT !^A%
This will work for all types of variable (integer, floating-point, string, array etc.) but in the case of a normal string variable the address returned is not that of the first character of the string but of the 4-byte string descriptor (see the CALL statement for details of string descriptors). Therefore the address of the string itself is !^string$ >>> 16.

In the case of an array the address returned by ^array() is that of a pointer to the array parameter block, therefore the address of the parameter block is !^array() AND &FFFF. To obtain the address of the array data you should specify the name of the first element, e.g. ^array(0).

Knowing the memory address of a variable may seem to be of little value but can be useful in special circumstances. For example In assembly language code you might want to copy the address of a BBC BASIC (integer) variable into one of the processor's registers:

ld hl,^variable%
Another use is to alter the byte-order of a variable, for example from little-endian to big-endian. The following code segment reverses the byte-order of the value stored in A%:
SWAP ?(^A%+0), ?(^A%+3)
SWAP ?(^A%+1), ?(^A%+2)


Operators and Special Symbols

The following list is a rather terse summary of the meaning of the various operators and special symbols used by BBC BASIC (Z80). It is provided for reference purposes; you will find more detailed explanations elsewhere in this manual.

? A unary and dyadic operator giving 8 bit indirection.
! A unary and dyadic operator giving 32 bit indirection.
" A delimiting character in strings. Strings always have an even number of " in them. " may be introduced into a string by the escape convention "".
# Precedes reference to a file channel number (and is not optional).
$ As a suffix on a variable name, indicates a string variable. As a prefix indicates a 'fixed string' e.g. $A="WOMBAT" Store WOMBAT at address A followed by CR.
% As a suffix on a variable name, indicates an integer (signed 32-bit) variable. As a prefix (BBC BASIC version 5 or later only) indicates a binary constant e.g. %11101111.
& As a suffix (BBC BASIC version 5 or later only) on a variable name, indicates a byte (unsigned 8-bit) variable. As a prefix Indicates a hexadecimal constant e.g. &EF.
' A character which causes new lines in PRINT or INPUT.
( ) Objects in parentheses have highest priority.
= 'Becomes' for LET statement and FOR, 'result is' for FN, relation of equal to on integers, reals and strings.
== (BBC BASIC version 5 or later only) Relation of equal to (alternative to =).
- Unary negation and dyadic subtraction on integers and reals.
* Binary multiplication on integers and reals; statement indicating operating system command (*DIR, *OPT).
: Multi-statement line statement delimiter.
; Suppresses forthcoming action in PRINT. Comment delimiter in the assembler. Delimiter in VDU and INPUT.
+ Unary plus and dyadic addition on integers and reals; concatenation between strings.
, Delimiter in lists.
. Decimal point in real constants; abbreviation symbol on keyword entry; introduce label in assembler; (BBC BASIC version 5 or later only) array dot-product operator.
< Relation of less than on integers, reals and strings.
<< Left-shift operator (signed or unsigned, BBC BASIC version 5 or later only).
> Relation of greater than on integers, reals and strings.
>> Right-shift operator (signed, BBC BASIC version 5 or later only).
>>> Right-shift operator (unsigned, BBC BASIC version 5 or later only).
/ Binary division on integers and reals.
\ Alternative comment delimiter in the assembler.
<= Relation of less than or equal on integers, reals and strings.
>= Relation of greater than or equal on integers, reals and strings.
<> Relation of not equal on integers, reals and strings.
[ ] Delimiters for assembler statements. Statements between these delimiters may need to be assembled twice in order to resolve any forward references. The pseudo operation OPT (initially 3) controls errors and listing.
^ Binary operation of exponentation between integers and reals; (BBC BASIC version 5 or later only) the address of operator.
~ A character in the start of a print field indicating that the item is to be printed in hexadecimal. Also used with STR$ to cause conversion to a hexadecimal string.
(BBC BASIC version 5 or later only):
|A unary operator giving floating-point indirection. A delimiter in the VDU statement.
+= Assignment with addition (A += B is equivalent to A = A + B)
−= Assignment with subtraction (A −= B is equivalent to A = A − B)
*= Assignment with multiplication (A *= B is equivalent to A = A * B)
/= Assignment with division (A /= B is equivalent to A = A / B)
AND= Assignment with AND (A AND= B is equivalent to A = A AND B)
DIV= Assignment with DIV (A DIV= B is equivalent to A = A DIV B)
EOR= Assignment with EOR (A EOR= B is equivalent to A = A EOR B)
MOD= Assignment with MOD (A MOD= B is equivalent to A = A MOD B)
OR= Assignment with OR (A OR= B is equivalent to A = A OR B)


Keywords

It is not always essential to separate keywords with spaces, for example DEGASN1 is equivalent to DEG ASN 1: both the DEG and the ASN are recognized as keywords. However ADEGASN1 is treated as a variable name: neither DEG nor ASN is recognized as a keyword.

In general variable names cannot start with a keyword, but there are some exceptions. For example the constant PI and the pseudo-variables LOMEM, HIMEM, PAGE, and TIME can form the first part of the name of a variable. Therefore PILE and TIMER are valid variable names although PI$ and TIME% are not.

37 out of the total of 138 keywords are allowed at the start of a variable name; they are shown in bold type in the table below. 23 keywords are only available in BBC BASIC version 5 or later; they are indicated with an asterisk.

Keywords Available

ABS ACS ADVAL AND ASC ASN
ATN BGET BPUT BY* CALL CASE*
CHAIN CHR$ CIRCLE* CLEAR CLG CLOSE
CLS COLOR COLOUR COS COUNT DATA
DEF DEG DIM DIV DRAW ELLIPSE*
ELSE END ENDCASE* ENDIF* ENDPROC ENDWHILE*
ENVELOPE EOF EOR ERL ERR ERROR
EVAL EXIT* EXP EXT FALSE FILL*
FN FOR GCOL GET GET$ GOSUB
GOTO HIMEM IF INKEY INKEY$ INPUT
INSTALL* INSTR( INT LEFT$( LEN LET
LINE LN LOCAL LOG LOMEM MID$(
MOD MODE MOUSE* MOVE NEXT NOT
OF* OFF ON OPENIN OPENOUT OPENUP
OR ORIGIN* OSCLI OTHERWISE* PAGE PI
PLOT POINT( POS PRINT PROC PTR
PUT QUIT* RAD READ RECTANGLE* REM
REPEAT REPORT RESTORE RETURN RIGHT$( RND
RUN SGN SIN SOUND SPC SQR
STEP STOP STR$ STRING$( SUM* SWAP*
SYS* TAB( TAN THEN TIME TINT*
TO TRACE TRUE UNTIL USR VAL
VDU VPOS WAIT* WHEN* WHILE* WIDTH
The following immediate-mode commands are strictly speaking not keywords:
AUTO DELETE EDIT LIST LISTO LOAD
NEW OLD RENUMBER SAVE


Debugging

"If debugging is the process of removing bugs, then programming must be the process of putting them in."

It is inevitable that programs will sometimes contain bugs. You may be able to write small programs which are error-free and work first time, but the larger your programs get the greater the likelihood that they will have errors. These fall into three categories:

Indentation

By default looping and nesting constructs in your program are indented when LISTed. This allows you to quickly spot errors such as:

Fast edit-run cycle

As BBC BASIC is an interpreted language (albeit a very fast one) it has the advantage of allowing you to edit and re-run a program instantly. After you have made a change to a program you don't have to wait for it to be re-compiled and re-linked before you can run it. Although trial-and-error debugging isn't to be encouraged, there are occasions when it is the most efficient way of solving a problem.

Immediate mode

If an untrapped error occurs at run time the program exits to immediate mode and displays an error message followed by the > prompt. At the prompt you can type any valid BASIC statement then press the Enter key, whereupon (as the name suggests) the statement will be executed immediately. This can be very useful in ascertaining the values of, or performing calculations on, variables; issuing 'star' commands or even calling procedures and functions.


Error handling

Default error handling

By default, if BBC BASIC detects an error while running a program it will immediately halt execution and report an error message and the line number (if any). This behaviour may often be adequate, but you have the option of trapping errors and writing your own code to handle them.

Reasons for trapping errors

There are a number of reasons why you might want to trap errors:

To make your program more 'friendly'

When you write a program for yourself, you know what you want it to do and you also know what it can't do. If, by accident, you try to make it do something which could give rise to an error, you accept the fact that BBC BASIC might terminate the program and return to immediate mode. However, when somebody else uses your program they are not blessed with your insight and they may find the program 'crashing out' without knowing what they have done wrong. Such programs are called 'fragile'. You can protect your user from much frustration if you display a more 'friendly' error report and fail 'gracefully'.

To ensure the error message is visible

The default error reporting writes the error message to the screen just like any other text output. Unfortunately there are several reasons why your program might not display a useful message, for example the text colours, font, size, position etc. are such that the message is invisible.

To allow cleanup operations to take place

There can be situations, particularly when calling Operating System functions, when aborting an operation 'mid stream' may leave the system in an unstable state; for example it might result in a memory leak. It could even, in unusual circumstances, crash BBC BASIC. In such cases your own error handler can carry out the necessary tidying-up operations before reporting the error and exiting gracefully.

To allow execution to continue

Although it is preferable to prevent errors occurring in the first place, there can be occasions when this is difficult or impossible to achieve, and it is better to allow the error to happen. In these circumstances error trapping allows the program to continue execution, possibly with some specific action being taken as a result.

Error trapping commands

The two main commands provided by BBC BASIC for error trapping and recovery are:
ON ERROR ....
and
ON ERROR LOCAL ....

ON ERROR

The ON ERROR command directs BBC BASIC to execute the statement(s) following ON ERROR when a trappable error occurs:
ON ERROR PRINT '"Oh No!":END
If an error was detected in a program after this line had been encountered, the message 'Oh No!' would be printed and the program would terminate. If, as in this example, the ON ERROR line contains the END statement or transfers control elsewhere (e.g. using GOTO) then the position of the line within the program is unimportant so long as it is encountered before the error occurs. If there is no transfer of control, execution following the error continues as usual on the succeeding line, so in this case the position of the ON ERROR line can matter.

As explained in the Program Flow Control sub-section, every time BBC BASIC encounters a FOR, REPEAT, GOSUB, FN, PROC or WHILE statement it 'pushes' the return address on to a 'stack' and every time it encounters a NEXT, UNTIL, RETURN, ENDWHILE statement or the end of a function or procedure it 'pops' the latest return address of the stack and goes back there. The program stack is where BBC BASIC records where it is within the structure of your program.

When an error is detected by BBC BASIC, the stack is cleared. Thus, you cannot just take any necessary action depending on the error and return to where you were because BBC BASIC no longer knows where you were.

If an error occurs within a procedure or function, the value of any parameters and LOCAL variables will be the last value they were set to within the procedure or function which gave rise to the error (the values, if any, they had before entry to the procedure or function are lost).

ON ERROR LOCAL

(BBC BASIC version 5 or later only)
The ON ERROR LOCAL command prevents BBC BASIC clearing the program stack. By using this command, you can trap errors within a FOR ... NEXT, REPEAT ... UNTIL or WHILE ... ENDWHILE loop or a subroutine, function or procedure without BBC BASIC losing its place within the program structure.

The following example program will continue after the inevitable 'Division by zero' error:

FOR n=-5 TO 5
  ok% = TRUE 
  ON ERROR LOCAL PRINT "Infinity" : ok% = FALSE
  IF ok% PRINT "The reciprocal of ";n;" is ";1/n
NEXT n
This is, of course, a poor use of error trapping. You should test for n=0 rather than allow the error to occur. However, it does provide a simple demonstration of the action of ON ERROR LOCAL. Also, you should test ERR to ensure that the error was the one you expected rather than, for example, Escape (ERR is a function which returns the number of the last error; it is explained later in this sub-section).

After the loop terminates (when 'n' reaches 6) the previous error trapping state is restored. Alternatively, you can explicitly restore the previous state using RESTORE ERROR.

You can call a subroutine, function or procedure to 'process' the error, but it must return to the loop, subroutine, function or procedure where the error was trapped:

x=OPENOUT "TEST"
FOR i=-5 TO 5
  ok% = TRUE
  ON ERROR LOCAL PROCerr : ok% = FALSE
  IF ok% PRINT#x,1/i
NEXT
CLOSE#x
:
x=OPENIN "TEST"
REPEAT
  INPUT#x,i
  PRINT i
UNTIL EOF#x
CLOSE#x
END
:
DEF PROCerr
IF ERR <> 18 REPORT:END
PRINT#x,3.4E38
ENDPROC
The position of the ON ERROR LOCAL within a procedure or function can be important. Consider the following two examples:
DEF PROC1(A)
ON ERROR LOCAL REPORT : ENDPROC
LOCAL B
....
DEF PROC1(A)
LOCAL B
ON ERROR LOCAL REPORT : ENDPROC
....
In the case of the first example, if an error occurs within the procedure, the formal parameter A will be automatically restored to its original value, but the LOCAL variable B will not; it will retain whatever value it had when the error occurred. In the case of the second example, both the formal parameter A and the LOCAL variable B will be restored to the values they had before the procedure was called.

ON ERROR or ON ERROR LOCAL?

If you use ON ERROR, BBC BASIC clears the program stack. Once your program has decided what to do about the error, it must re-enter the program at a point that is not within a loop, subroutine, function or procedure. In practice, this generally means somewhere towards the start of the program. This is often undesirable as it makes it difficult to build well structured programs which include error handling. On the other hand, you will probably only need to write one or two program sections to deal with errors.

At first sight ON ERROR LOCAL seems a more attractive proposition since BBC BASIC remembers where it is within the program structure. The one disadvantage of ON ERROR LOCAL is that you will need to include an error handling section at every level of your program where you need to trap errors. Many of these sections of program could be identical.

You can mix the use of ON ERROR and ON ERROR LOCAL within your program. A single ON ERROR statement can act as a 'catch all' for unexpected errors, and one or more ON ERROR LOCAL statements can be used when your program is able to recover from predictable errors. ON ERROR LOCAL 'remembers' the current ON ERROR setting, and restores it when the loop, procedure or function containing the ON ERROR LOCAL command is finished, or when a RESTORE ERROR is executed.

Error reporting

There are three functions, ERR, ERL, REPORT$ and one statement, REPORT, which may be used to investigate and report on errors. Using these, you can trap out errors, check that you can deal with them and abort the program run if you cannot.

ERR

ERR returns the error number (see the section entitled Error messages and codes).

ERL

ERL returns the line number where the error occurred. If an error occurs in a procedure or function call, ERL will return the number of the calling line, not the number of the line in which the procedure/function is defined. If an error in a DATA statement causes a READ to fail, ERL will return the number of the line containing the DATA, not the number of the line containing the READ statement. If the line is not numbered, ERL returns zero.

REPORT$

(BBC BASIC version 5 or later only)
REPORT$ returns the error string associated with the last error which occurred.

REPORT

REPORT prints out the error string associated with the last error which occurred. It is equivalent to PRINT REPORT$;

Error trapping examples

The majority of the following error trapping examples are all very simple programs without nested loops, subroutines, functions or procedures. Consequently, they use ON ERROR for error trapping in preference to ON ERROR LOCAL.

The example below does not try to deal with errors, it just uses ERR and REPORT to tell the user about the error. Its only advantage over BBC BASIC's normal error handling is that it gives the error number; it would probably not be used in practice. As you can see from the second run, pressing <ESC> is treated as an error (number 17).

ON ERROR PROCerror
REPEAT
  INPUT "Type a number " num
  PRINT num," ",SQR(num)
  PRINT
UNTIL FALSE
:
DEF PROCerror
PRINT
PRINT "Error No ";ERR
REPORT
END
Example run:
RUN
Type a number 1
         1         1
Type a number -2
        -2
Error No 21
Negative root

RUN Type a number <Esc> Error No 17 Escape
The example below has been further expanded to include error trapping. The only 'predictable' error is that the user will try a negative number. Any other error is unacceptable, so it is reported and the program aborted. Consequently, when <ESC> is used to abort the program, it is reported as an error. However, a further test for ERR=17 could be included so that the program would halt on ESCAPE without an error being reported.
ON ERROR PROCerror
REPEAT
 INPUT "Type a number " num
  PRINT num," ",SQR(num)
 PRINT
UNTIL FALSE
:
DEF PROCerror
PRINT
IF ERR=21 THEN PRINT "No negatives":ENDPROC
REPORT
END
This is a case where the placement of the ON ERROR statement is important. When PROCerror exits, execution continues after the ON ERROR statement, which in this case causes the program to restart from the beginning.

Example run:

RUN
Type a number 5
         5          2.23606798

Type a number 2 2 1.41421356
Type a number -1 -1 No negatives
Type a number 4 4 2
Type a number <Esc> Escape
The above example is very simple and was chosen for clarity. In practice, it would be better to test for a negative number before using SQR rather than trap the 'Negative root' error. A more realistic example is the evaluation of a user-supplied HEX number, where trapping 'Bad hex or binary' would be much easier than testing the input string beforehand.
ON ERROR PROCerror
REPEAT
  INPUT "Type a HEX number " Input$
  num=EVAL("&"+Input$)
  PRINT Input$,num
  PRINT
UNTIL FALSE
:
DEF PROCerror
PRINT
IF ERR=28 THEN PRINT "Not hex":ENDPROC
REPORT
END
The next example is similar to the previous one, but it uses the ON ERROR LOCAL command to trap the error.
REPEAT
  ON ERROR LOCAL PROCerror
  INPUT "Type a HEX number " Input$
  num=EVAL("&"+Input$)
  PRINT Input$,num
  PRINT
UNTIL FALSE
:
DEF PROCerror
PRINT
IF ERR=28 THEN PRINT "Not hex":ENDPROC
REPORT
END
Note that had ON ERROR (rather than ON ERROR LOCAL) been used in this case, an error would give rise to a Not in a REPEAT loop error at the UNTIL statement. This is because ON ERROR clears the program's stack.


Procedures and functions

Introduction

Procedures and functions are similar to subroutines in that they are 'bits' of program which perform a discrete function. Like subroutines, they can be performed (called) from several places in the program. However, they have two great advantages over subroutines: you can refer to them by name and the variables used within them can be made private to the procedure or function.

Arguably, the major advantage of procedures and functions is that they can be referred to by name. Consider the two similar program lines below.

IF name$="ZZ" THEN GOSUB 500 ELSE GOSUB 800

IF name$="ZZ" THEN PROC_end ELSE PROC_print
The first statement gives no indication of what the subroutines at lines 500 and 800 actually do. The second, however, tells you what to expect from the two procedures. This enhanced readability stems from the choice of meaningful names for the two procedures.

A function often carries out a number of actions, but it always produces a single result. For instance, the 'built in' function INT returns the integer part of its argument.

age=INT(months/12)
A procedure on the other hand, is specifically intended to carry out a number of actions, some of which may affect program variables, but it does not directly return a result.

Whilst BBC BASIC has a large number of pre-defined functions (INT and LEN for example) it is very useful to be able to define your own to do something special. Suppose you had written a function called FN_discount to calculate the discount price from the normal retail price. You could write something similar to the following example anywhere in your program where you wished this calculation to be carried out.

discount_price=FN_discount(retail_price)
It may seem hardly worth while defining a function to do something this simple. However, functions and procedures are not confined to single line definitions and they are very useful for improving the structure and readability of your program.

Names

The names of procedures and functions MUST start with PROC or FN and, like variable names, they cannot contain spaces. This restriction can give rise to some pretty unreadable names. However, the underline character can be used to advantage. Consider the procedure and function names below and decide which is the easier to read.
PROCPRINTDETAILS      FNDISCOUNT

PROC_print_details FN_discount
Function and procedure names may end with a '$'. However, this is not compulsory for functions which return strings.

Function and procedure definitions

Starting a definition

Function and procedure definitions are 'signalled' to BBC BASIC by preceding the function or procedure name with the keyword DEF. DEF must be at the beginning of the line. If the computer encounters DEF during execution of the program, the rest of the line is ignored. Consequently, you can put single line definitions anywhere in your program.

The function/procedure body

The 'body' of a procedure or function must not be executed directly - it must be performed (called) by another part of the program. Since BBC BASIC only skips the rest of the line when it encounters DEF, there is a danger that the remaining lines of a multi-line definition might be executed directly. You can avoid this by putting multi-line definitions at the end of the main program text after the END statement. Procedures and functions do not need to be declared before they are used and there is no speed advantage to be gained by placing them at the start of the program.

Ending a definition

The end of a procedure definition is indicated by the keyword ENDPROC. The end of a function definition is signalled by using a statement which starts with an equals (=) sign. The function returns the value of the expression to the right of the equals sign.

Single line functions/procedures

For single line definitions, the start and end are signalled on the same line. The first example below defines a function which returns the average of two numbers. The second defines a procedure which clears from the current cursor position to the end of the line (on a 40 column screen):
DEF FN_average(A,B) = (A+B)/2
DEF PROC_clear:PRINT SPC(40-POS);:ENDPROC

Extending the language

You can define a whole library of procedures and functions and include them in your programs. By doing this you can effectively extend the scope of the language. For instance, BBC BASIC does not have a 'clear to end of screen' command. The example below is a procedure to clear to the end of 'screen' (BASIC's output window) with an 80 column by 25 row display (e.g. MODE 3). The three variables used (i%, x%, and y%) are declared as LOCAL to the procedure (see later).
DEF PROC_clear_to_end
LOCAL i%,x%,y%
x%=POS:y%=VPOS
REM If not already on the last line, print lines of 
REM spaces which will wrap around until the last line
IF y% < 24 FOR i%=y% TO 23:PRINT SPC(80);:NEXT
REM Print spaces to the end of the last line.
PRINT SPC(80-x%);
REM Return the cursor to its original position
PRINT TAB(x%,y%);
ENDPROC

Passing parameters

When you define a procedure or a function, you list the parameters to be passed to it in brackets. For instance, the discount example expected one parameter (the retail price) to be passed to it. You can write the definition to accept any number of parameters. For example, we may wish to pass both the retail price and the discount percentage. The function definition would then look something like this:
DEF FN_discnt(price,pcent)=price*(1-pcent/100)
In this case, to use the function we would need to pass two parameters.
retail_price=26.55
discount_price=FN_discount(retail_price,25)
or
price=26.55
discount=25
price=FN_discount(price,discount)
or
price=FN_discount(26.55,25)

Formal and actual parameters

The value of the first parameter in the call to the procedure or function is passed to the first variable named in the parameter list in the definition, the second to the second, and so on. This is termed 'passing by value' (however note that arrays and structures are 'passed by reference'). The parameters declared in the definition are called 'formal parameters' and the values passed in the statements which perform (call) the procedure or function are called 'actual parameters'. There must be as many actual parameters passed as there are formal parameters declared in the definition.
FOR I% = 1 TO 10
PROC_printit(I%) : REM I% is the Actual parameter
NEXT
END

DEF PROC_printit(num1) : REM num1 is the Formal parameter
PRINT num1
ENDPROC
The formal parameters must be variables, but the actual parameters may be variables, constants or expressions. When the actual parameter is a variable, it need not be (and usually won't be) the same as the variable used as the formal parameter. Formal parameters are automatically made local to the procedure or function.

You can pass a mix of string and numeric parameters to the procedure or function, and a function can return either a string or numeric value, irrespective of the type of parameters passed to it. However, you must make sure that the parameter types match up. The first example below is correct; the second would give rise to an 'Incorrect arguments' error message and the third would cause a 'Type mismatch' error to be reported.

Correct
PROC_printit(1,"FRED",2)
END
:
DEF PROC_printit(num1,name$,num2)
PRINT num1,name$,num2
ENDPROC
Incorrect arguments error
PROC_printit(1,"FRED",2,4)
END
:
DEF PROC_printit(num1,name$,num2)
PRINT num1,name$,num2
ENDPROC
Type mismatch error
PROC_printit(1,"FRED","JIM")
END
:
DEF PROC_printit(num1,name$,num2)
PRINT num1,name$,num2
ENDPROC

Local variables

You can use the LOCAL statement to declare variables for use locally within individual procedures or functions (the formal parameters are also automatically local to the procedure or function declaring them). Changing the values of local variables has no effect on variables of the same name (if any) elsewhere in the program.

Declaring variables as LOCAL initialises them to zero (in the case of numeric variables) or null/empty (in the case of string variables). Declaring variables as PRIVATE causes them to retain their values from one call of the function/procedure to the next. If an array or structure is made LOCAL or PRIVATE it must be re-DIMensioned before use.

Variables which are not formal parameters nor declared as LOCAL are known to the whole program, including all the procedures and functions. Such variables are called global.

Recursive functions/procedures

Because the formal parameters which receive the passed parameters are local, all procedures and functions can be recursive. That is, they can call themselves. But for this feature, the short example program below would be difficult to code. It is the often used example of a factorial number routine (the factorial of a number n is n * n−1 * n−2 * .... * 1. Factorial 6, for instance, is 6 * 5 * 4 * 3 * 2 * 1 = 720).
REPEAT
  INPUT "Enter an INTEGER less than 35 "num
UNTIL INT(num)=num AND num<35
fact=FN_fact_num(num)
PRINT num,fact
END
:
DEF FN_fact_num(n)
IF n=1 OR n=0 THEN =1
REM Return with 1 if n= 0 or 1
=n*FN_fact_num(n-1)
REM Else go round again
Since 'n' is the input variable to the function FN_fact_num, it is local to each and every use of the function. The function keeps calling itself until it returns the answer 1. It then works its way back through all the calls until it has completed the final multiplication, when it returns the answer. The limit of 35 on the input number prevents the answer being too big for the computer to handle.

Passing arrays to functions and procedures

(BBC BASIC version 5 or later only)

BBC BASIC allows you to pass an entire array (rather than just a single element) to a function or procedure. Unlike single values or strings, which are passed to a function or procedure by value, an array is passed by reference. That is, a pointer to the array contents is passed rather than the contents themselves. The consequence of this is that if the array contents are modified within the function or procedure, they remain modified on exit from the function or procedure. In the following example the procedure PROC_multiply multiplies all the values in a numeric array by a specified amount:

DIM arr(20)
FOR n%=0 TO 20 : arr(n%) = n% : NEXT
PROC_multiply(arr(), 2)
FOR n%=0 TO 20: PRINTarr(n%) : NEXT 
END
:
DEF PROC_multiply(B(), M)
LOCAL n%
FOR n% = 0 TO DIM(B(),1)
  B(n%) = B(n%) * M
NEXT
ENDPROC
Note the use of DIM as a function to return the number of elements in the array.

The advantage of passing an array as a parameter, rather than accessing the 'global' array directly, is that the function or procedure doesn't need to know the name of the array. Ideally a FN/PROC shouldn't need to know the names of variables used in the main program from which it is called, and the main program shouldn't need to know the names of variables contained in a function or procedure it calls.

Using parameters for output

(BBC BASIC version 5 or later only)

Although function and procedure parameters are usually inputs, it is possible to specify that they can also be outputs by using the keyword RETURN in the definition:

DEF PROCcomplexsquare(RETURN r, RETURN i)
If a RETURNed parameter is modified within the function or procedure, it remains modified on exit. This is the case even if the actual parameter and the formal parameter have different names.

Suppose you want to write a function which returns a complex number. Since a complex number is represented by two numeric values (the real part and the imaginary part) a conventional user-defined function, which can return only a single value, is not suitable. Conventionally you would have to resort to using global variables or an array or structure to return the result, but by using RETURNed parameters this can be avoided.

The following example shows the use of a procedure to return the square of a complex number:

INPUT "Enter complex number (real, imaginary): " real, imag
PROCcomplexsquare(real, imag)
PRINT "The square of the number is ";real " + ";imag " i"
END
DEF PROCcomplexsquare(RETURN r, RETURN i)
LOCAL x,y 
x = r : y = i
r = x^2 - y^2
i = 2 * x * y
ENDPROC

You can use a similar technique to return strings rather than numbers. The following example, rather pointlessly, takes two strings and mixes them up by exchanging alternate characters between them:

INPUT "Enter two strings, separated by a comma: " A$, B$
PROCmixupstrings(A$, B$)
PRINT "The mixed-up strings are " A$ " and " B$
END
DEF PROCmixupstrings(RETURN a$, RETURN b$)
LOCAL c$, I%
FOR I% = 1 TO LEN(a$) STEP 2
  c$ = MID$(a$,I%,1)
  MID$(a$,I%,1) = MID$(b$,I%,1)
  MID$(b$,I%,1) = c$
NEXT I%
ENDPROC
You can also use this facility to create a variable whose name is determined at run-time, something which is otherwise impossible to achieve:
INPUT "Enter a variable name: " name$
INPUT "Enter a numeric value for the variable: " value$
dummy% = EVAL("FNassign("+name$+","+value$+")")
PRINT "The variable "name$" has the value ";EVAL(name$)
END
DEF FNassign(RETURN n, v) : n = v : = 0

Returning arrays from procedures and functions

(BBC BASIC version 5 or later only)

It is possible to declare an array within a function or procedure and return that new array to the calling code. To do that you must pass an undeclared array as the parameter and use the RETURN keyword in the function or procedure definition:

PROCnewarray(alpha())
PROCnewarray(beta())
PROCnewarray(gamma())

DEF PROCnewarray(RETURN a())
DIM a(3, 4, 5)
...
ENDPROC
Note: You cannot use this technique to declare LOCAL arrays.

Left CONTENTS

CONTINUE Right


Best viewed with Any Browser Valid HTML 4.0!
© Doug Mounter and Richard Russell 2025