Function
A function is similar to the meaning of a mathematical definition. A single return value, the result of the function, is derived from one or more input parameters. In the following example the result of the absolute function for the parameter given by variable X is calculated
X = -1 : PRINT ABS(X)
Screen output:
1
Subroutines can be also regarded as a function if this routine takes its parameters and returns values indirectly by means of variables. In Commodore BASIC all variables have global scope, they can't be hidden in subroutine calls as local variables. They can be accessed from the whole BASIC program from everywhere.
10 A = 10: B = 5 20 GOSUB 100 30 PRINT A, B 99 END 100 REM *** Swap function *** 101 C = A : A = B : B = C : C = 0: RETURN
Screen output:
5 10
In general, BASIC supports three classes of functions depending on the type of the return value or the calling environment:
- numeric functions
- string functions
- printing functions
The BASIC V2 of the C64 includes basic mathematical functions like ABS, ATN, COS, EXP, INT, LOG, SGN, SIN, SQR and TAN.
A few special functions, which returns also a numeric value:
- RND provides a pseudo random number,
- DEF let one define a self-defined mathematical function which can be called by means of FN,
- USR offers a way to handover expressions to a machine language program and put back a (numeric or string) result to the BASIC's calling environment,
- PEEK returns the contents of memory location referred by a given memory address,
- FRE gets the available (unused) RAM memory in BASIC V2, which forces to run the garbage collection as a side-effect,
- POS reads the actual position (e.g. cursor on screen) for the current output device
There are also some numerical functions for string handling (for string parameters): ASC, LEN, VAL
String functions returns a string from input based on strings and/or numeric expressions:
Printing functions are only usable in typical output commands like PRINT, PRINT# or CMD. As opposed to the other function classes the return value is not a real value which is used for further calculations, it has only an effect on some output attribute: