202 DEF define Purpose The word DEF is used to inform the computer that a procedure or function is about to be defined. Once the computer has been informed that this procedure or function exists, then the procedure or function can be called by name anywhere in the program. Definitions of procedures and functions must not occur in the body of a program . They should be placed in a separate section which is not executed – for example after the final END in the program. This also aids readability. The language BASIC has many predefined functions which the computer already knows about. For example, the function SQR enables it to calculate the square root of a number.
Often though, it is useful to be able to define your own functions. For example, you might want to have a function which calculates the VAT inclusive price of a product from the basic sale price by multiplying by 1.15. A function always produces a result so you can write X=FNST . A procedure, on the other hand, is used to perform a number of actions, but it does not by itself produce a numerical result. For example, a procedure might be set up to clear the screen and draw a number of lines on the screen. You may well feel confused, but do not be put off! The use of procedures and functions may be difficult to understand at first but it is well worth the effort.
Their use greatly enhances the readability and reliability of programs. The section below gives a more detailed explanation of the use of procedures and functions. It should be read in conjunction with the examples which follow. Both procedures and functions may contain local variables which are declared using the word LOCAL . In the third example given below, K is declared as a local variable. This means that although K is used in this procedure its value is notdefined when the procedure finishes. In fact the variable K might well be used elsewhere in the program. The variable K, elsewhere within the program, would not be altered by the use of the local variable K within the procedure.
Any variable which is not declared as LOCAL will be available outside the procedure, in other words to the rest of the program. Also, both procedures and functions may have parameters passed to them. Look at the first example program below: line 1010 says 1010 DEF FNST(g)=1.15*g