 BBC BASIC Programmers' Reference

Site Tools

returning_20an_20array_20from_20a_20function

Returning an array from a function

by Richard Russell, November 2012

Modifying the contents of an array (i.e. its elements) within a PROC or FN is straightforward, because arrays are passed by reference and therefore any modifications to their contents remain intact after the FN or PROC returns.

However this necessarily means that the array must first be created (DIMensioned) outside the FN or PROC, and this may not always be convenient or desirable. The alternative is to create the array inside the function and then to return it to the caller. The conventional way of doing that is to use the RETURN qualifier; for example this procedure creates an identity matrix (having ones on the leading diagonal and zeroes elsewhere):

DEF PROCidn(RETURN i(), n%)
LOCAL i%
DIM i(n%, n%)
FOR i% = 0 TO n%
i(i%,i%) = 1
NEXT
ENDPROC

The procedure is called with two parameters: the array to be created (which must not have been previously dimensioned) and the required size (maximum row and column index), for example:

PROCidn(identity(), 3)

This works well, but in one respect it is not particularly 'satisfying'. Normally, when you want to return a value (numeric or string) from a sub-module you would use a function (FN) rather than a procedure (PROC). A function provides a more natural means to return a value, since it may be assigned directly to a variable:

result = FNfunction(parameters)

Wouldn't it be nice if you could do the same with an array, in other words create an array within a function and return it to the caller in the same way as a regular function returns a number or a string? In fact, with a little bit of trickery, you can!

Using the example of a function to create an identity matrix, this is how you would code it:

DEF FNidn(n%)
LOCAL i%, !^i()
DIM i(n%, n%)
FOR i% = 0 TO n%
i(i%,i%) = 1
NEXT
= !^i()

Note particularly the use of !^ in both the LOCAL statement and when the array is returned from the function. The function can then be called as follows:

!^identity() = FNidn(3)

Again, note the use of an array pointer using !^.

This may be a useful technique when translating from a language that can directly return an array from a function, or simply to create a more elegant code solution. 