Keyboard shortcuts

Press ← or → to navigate between chapters

Press S or / to search in the book

Press ? to show this help

Press Esc to hide this help

Returning arrays

A function can hand back a whole array: write ( ) after the result type, as in as int32( ). The result is an ordinary dynamic array.

'' A function returns an array when its result type ends in ( ).

'' A brace list: the array is sized to the list, indexed from 0.
function Vowels( ) as ustring( )
    return { "a", "e", "i", "o", "u" }
end function

'' A local array, built in a loop. It is moved to the caller, not
'' copied, and keeps the bounds the function gave it.
function Squares( byval n as int32 ) as int32( )
    dim as int32 result( )
    redim result( 1 to n )
    for i as int32 = 1 to n
        result( i ) = i * i
    next
    return result
end function

'' var takes the result with its type and bounds.
var v = Vowels( )
print "vowels " & lbound( v ) & " to " & ubound( v ) & ", last: " & v( 4 )

var sq = Squares( 5 )
print "squares " & lbound( sq ) & " to " & ubound( sq ) & ", sq( 5 ) ="; sq( 5 )

'' A result can be walked directly; it is freed after the loop.
for each n in Squares( 3 )
    print n;
next
print

'' Assigning a result to an existing dynamic array replaces its contents.
dim as int32 table( )
table = Squares( 2 )
print "table " & lbound( table ) & " to " & ubound( table ) & ":"; _
      table( 1 ); table( 2 )

Output

vowels 0 to 4, last: u
squares 1 to 5, sq( 5 ) = 25
 1 4 9
table 1 to 2: 1 4

return takes one of three things:

  • a brace list, as in Vowels. The array is sized to the list and indexed from 0.
  • a local array, as in Squares. It is moved to the caller rather than copied, and keeps its bounds, so sq runs from 1 to 5.
  • a call to another function that returns an array of the same type.

The caller owns the result. var sq = Squares( 5 ) takes it with its type and bounds. Assigning to an existing dynamic array, table = Squares( 2 ), frees what table held and takes the new array. A result used in place, like the one for each walks, is freed when the statement ends.

Only an array that belongs to the function can be moved out. Returning a parameter is refused with TKO0840: 'a' is not a local array of this procedure, so returning it would need a copy, which is not supported yet; return a local array or a brace list. To return a changed copy of a parameter, build a local array from it and return that.

dim r( ) as int32 = Squares( 3 ) is refused too (TKO0612: var-len array 'r' cannot be initialized): use var, or declare the array first and assign to it.

Activities

  1. Write function Evens( byval n as int32 ) as int32( ) returning the first n even numbers, indexed from 1.
  2. Write function Doubled( values( ) as const int32 ) as int32( ) that returns a new array with every element doubled and the same bounds.