previous page next page reference home emBASIC home page

6 Function definitions

6.1 Introduction

A function definition defines a user-defined function object. A function definition is an executable statement.
The function definition does not execute the function body; this gets executed only when the function is called.
Examples:

FUNCTION F (X AS INT) AS LONG
    LOCAL RET AS LONG
    IF (X <= 1) THEN
        RETURN 1
    END
    RET = X * F (X - 1)
ENDFUNC RET

PROCEDURE PR (X AS INT)
    ...
ENDPROC

6.2 Function arguments

Parameters to functions and procedures are passed by value: local variables are created and initialised by values of call expressions.
There is a way to pass parameters by name so assignments to formal parameters result in assignment to actual ones. This allows to change the value of the variable in the calling program. As this is usually not desired, use care when passing by reference.
To do it, prefix the name of the formal parameter with the keyword REF:

PROCEDURE clear(REF dt AS my_struct)
FUNCTION color(REF col_vec[] as STRING) as STRING

To declare a parameter-array one must indicate the number of it's dimensions: [ ] for a one-dimensional array, [,] -for two-dimensional and so on. The size of arrays is taken from the actual parameter.
Currently this is the only way to pass compound elements (arrays and structures) to functions as a whole.
It is possible to pass by reference a whole row or plane of a multi-dimensional array (but not a range).