This article looks at the FN keyword, used to define functions, which are like procedures that can return a value.
Functions are a mechanism by which the programmer can execute a named block of code, designed to do two things:
They are principally used when a PROCedure is required, but a value returned without changing one of the parameters, or providing a return parameter. For more information about PROCedures, the reader may consult this article.
A general overview of functions and procedures can be found in the Procedure, Subroutine or Function? article.
A FuNction can appear in one of two locations, depending on whether it is a single line or multi-line function. A single line function is one which returns a value after performing some work, all in one line, whereas a multi-line function is spread over several lines.
This may seem obvious, but if a multi-line FuNction is defined inside a code block, then the code statements following its definition will be executed out of sequence. On the other hand, a single line function may appear inside a code block, because it will not be executed unless called by name.
We define a function as follows:
A single line function might be defined as:
Note that we have used the : character to separate the statements in the line. Essentially, any single line function could be spread over multiple lines, and defined at the end of the program, and most multi-line functions can be defined in-line in a single line.
However, this will impact readability. For more information on choosing appropriate names, readability and so on, this article might be of help.
The correct place to define a multi line function is at the end of the main application code, after the END statement:
The return value can be any sensible value, numerical or string. It is not necessary to include a return type in the definition as with some BASIC language implementations.
To return the value, simply enter the = sign on an empty line, followed by an expression. The expression can be any mixture of operators, variables and constants that yield a single result. It is also possible to use conditional statements to return one of a set of values.
As with PROCedures, we can pass parameters by value or by reference. The default behavior is to pass them by value, thus they become fixed, constant values when used inside the function. To override this, the RETURN statement can be used, however, since the goal of a function is to return a set value, passing by reference for the purpose of returning a value might seem to confuse the issue.
User defined structures and arrays are passed by reference as standard, as in other languages such as C.