Sinclair QL Beginner's Manual page 106

Hide thumbs Also See for QL:
Table of Contents

Advertisement

In the main program actual parameters 3 and 4 are used. The procedure definition has a formal
parameter num, which takes the value passed to it from the main program. Note that the formal
parameters must be in brackets, but that actual parameters need not be.
EXAMPLE
Now suppose the working variable, "price", was also used in the main program, meaning something
else, say the price of a glass of lager 70p. The following program fails to give the desired result.
100 REMark Global price
110 LET price = 70
120 item 3
130 item 4
140 PRINT ! price !
150 DEFine PROCedure item(num)
160
IF num <= 3 THEN LET price = 300 + 10*num
170
IF num >= 4 THEN LET price = 12*num
180
PRINT ! price !
190 END DEFine
Output
330 48 48
The price of the lager has been altered by the procedure. We say that the variable, price, is global
because it can be used anywhere in the program.
Make the procedure variable, price, LOCAL to the procedure. This means that SuperBASIC will treat
it as a special variable accessible only within the procedure. The variable, "price", in the main program
will be a different thing even though it has the same name.
100 REMark LOCAL price
110 LET price = 70
120 item 3
130 item 4
140 PRINT ! price !
150 DEFine PROCedure item(num)
160
LOCaL price
170
IF num <= 3 THEN LET price = 300 + 10*num
180
IF num >= 4 THEN LET price = 12*num
190
PRINT ! price !
200 END DEFine
Output
330 48 70
This time everything works properly. Line 70 causes the procedure variable, price to be internally
marked as 'belonging' only to the procedure, item. The other variable, price is not affected. You can
see that local variables are useful things.
EXAMPLE
Local variables are so useful that we automatically make procedure formal parameters local. Though
we have not mentioned it before parameters such as num in the above programs cannot interfere with
main program variables. To prove this we drop the LOCAL statement from the above program and
use num for the price of lager. Because num in the procedure is local everything works.
Program

Advertisement

Table of Contents
loading

Table of Contents