Arrays as arguments to functions

Blitz3D Forums/Blitz3D Programming/Arrays as arguments to functions

Almo(Posted 2010) [#1]
Is it possible to pass an array declared as local to another function as an argument?


Yasha(Posted 2010) [#2]
Yes.

Local myArray[10],i

For i=1 To 10
	myArray[i]=i
Next

SquareArray myArray

PrintArray myArray

WaitKey
End


Function SquareArray(ar[10])
	Local i
	
	For i=1 To 10
		ar[i]=ar[i]*ar[i]
	Next
End Function

Function PrintArray(ar[10])
	Local i
	
	For i=1 To 10
		Write " "+ar[i]
	Next
	Print ""
End Function


The array is passed to the function by name only. The array parameter to the function must have the same type and size as the original array. Most importantly, the array isn't copied - it's passed directly, and altered in place (if it's altered) by the receiving function, as demonstrated above.

Incidentally, there's a really neat use for this when porting annoying C code, too. Where a C function takes a variable by reference so it can return multiple values, you can declare an array of size 0 and pass it to the receiving function. Since Blitz optimises numeric constants, this is nearly as fast as using a normal local variable and lets you return as many variables from a function as you like! Saves having to rewrite the whole function to return objects or single values only.


Almo(Posted 2010) [#3]
Awesome, thanks for the help. :)


_PJ_(Posted 2010) [#4]

this is nearly as fast as using a normal local variable and lets you return as many variables from a function as you like! Saves having to rewrite the whole function to return objects or single values only.


This is great! I have begun making use of this where working with 3D coords...
Where you'd normally need to process each dimension separately (calling a function 3 times or 3 separate functions) for X, Y and Z, or Pitch, Yaw and Roll etc. By using this method, you can return an array containing
X,Y and Z in one go!

... just as an example!