Function Definition
A function is defined with the following syntax:
{ scope } name ( { type input { WIDTH width }, ... } ) ( { type output { WIDTH width }, ... } ) body END;
There are two sets of variables defined in the function declaration; the first are the input parameters to the function, the second the return or output parameters.
- Scope
- The scope of the function, which defines where else in the program it is visible and can be called from. May be
GLOBAL
,INTERNAL
,LOCAL
or not defined. If not defined, the default isGLOBAL
. See Function Scopes for further information. - Function Name
- A valid function name starts with a letter or underscore and is then followed by any number of letters, numbers or underscores.
- Input Parameters
- Provide input values for the function to consume. The input arguments are passed into the function by value, so changing the value within this function does not affect the variable's value outside the function (except in the case of a FILE variable, where the file position may be changed).
- Output Parameters
- Provide a way for the function to return results back to the caller. The output arguments are passed into the function by reference. If a value is changed here, the change will be reflected in the variable in the calling function.
- Function Body
- The function body consists of the local variable declarations and then the statements. All local variables must be declared before any statements.
Example
LOCAL Increment(INT x)(INT result) result := x + 1; END;
If a width is specified for an argument, the argument (input or output) will be set to that width on entry to the function.
Example
LOCAL Increment(INT x WIDTH 10)(INT result WIDTH 10) result := x + 1; END;
In the above example, both 'x' and 'result' will be set to 10 bits wide.
Function Declaration
If a function with a single return argument is going to be used in an expression (see XJEase function calls in expressions), it must be defined before it can be used. Sometimes it is inconvenient or impossible to define functions in the necessary order, in which case a function can be declared without a body using the syntax:
{ scope } DECLARE name ( { type , ... } ) ( { type , ... } );
The function can then be used before it is defined, for example:
Example
LOCAL DECLARE Square(INT)(INT); GLOBAL PrintSquares()() INT i; FOR i := 0 FOR 10 PRINT("Square of ", i, " is ", Square(i), "\n"); END; END; LOCAL Square(INT in)(INT out) out := in * in; END;
If a scope is defined in the declaration, a matching scope must be specified in the function implementation otherwise an error will be raised.
XJTAG v4.1.100