Warning
You're browsing the old v2.x documentation. This version is no longer maintained. Click here to go the v3.x documentation.
This is an old revision of the document!
Table of Contents
FUN ... ENDFUN
Since version 2.2
Syntax:
fun <fun_name><sigil> [(<arg1>, <arg2>, <argn> ...)] [<statements>] return <expression> endfun
The FUN … ENDFUN
directives are used for defining a user function. Functions are similar to procedures with the exception that:
- They must return a value
- They can be called from within an expression
Defining functions
Define your functions /before/ calling them, preferably in the beginning of your source file, like in the example bellow:
fun sum_of_integers(a, b) return a + b endfun
To define a function of a type other than integer as well as defining parameters other than integers, use sigils:
fun sum_of_bytes!(a!, b!) return a! + b! endfun
It is valid to have more than one RETURN
statements in a function:
fun max(a, b) if a > b then return a else return b endif endfun
Note there are no such things as void functions in XC=BASIC and the following will not work:
fun dont_do_this(x) rem -- no return statement endfun
If you want a routine that does not return a value, use Procedures instead.
Parameterless functions
You can omit the parameter list, but bear in mind that you still have to write the empty parentheses:
fun no_params() ... endfun
Calling functions
You can call a function from within an expression by using the function name, sigil and the argument list in parentheses, for example:
let x! = my_function!(a, b!) * 2
Note that in the example above my_function!
is a function that returns a byte and accepts an integer and a byte as arguments.
Important note: you must pass exactly the same amount of parameters and the parameter types must match those in the function definition.
Recursion
While procedures do support direct recursion, functions don't.