What am I misunderstanding about arrays?

in Xojo, the Array object itself is always passed by reference, so a function gets a pointer to the actual array, and any changes made in the function are visible on the original array outside the function.

You can also pass the Array parameter ByRef but this means something different: inside a function with a ByRef Array parameter, the function can change the actual reference itself.

Imagine this:


Public Sub foo(x() as integer)
  x(0) = 99
  x = nil // this has no effect outside the function
End Sub
var a() as integer = Array(1,2,3)

Call foobar(a)  // now a() contains (99,1,3)

vs. using ByRef

Public Sub bar(ByRef x() as integer)
  x = Array(7,8,9)
End Sub

var a() as integer = Array(1,2,3)
var b() as integer = a  // b is a reference, pointing to a()

Call bar(b)

// at this point, 
// a and b now point to different array objects
// a = (7,8,9)
// b = (1,2,3) 

Subtle, but important difference.

3 Likes