Search code examples
arraysfunctionvb6

Visual basic 6.0: function returning array


Is there better way how to create function returning array than:

function foo
 Dim bar(1 to 2)as double
 bar(1)=1
 bar(2)=2
 foo=bar
end function

and in code:

arrayx=foo

Because when I declare Dim arrayx(1 to 2) as double it throws an error "can't assign array" When I don't declare the variable arrayx it doesn't seem to have any problems.


Solution

  • As Matt suggests, this error:

    Compile error: Can't assign to array

    stems from the fact that you've tried to assign the return value of Foo() to a fixed array, rather than a dynamic array. You simply need to indicate to the compiler that the variable you're declaring is an array, not the actual size of the array. It will figure out the size based on the size of the array that is returned.

    Additionally, you should always specify a return value type for your functions. You do that in VB by placing an As Type clause at the end of the function declaration. In this case, you want an array of doubles, written as Double().

    So, rewrite your code to look like this, incorporating both of those changes:

    Function Foo() As Double()      ' note the specification of a return value
       Dim bar(1 To 2) As Double
       bar(1) = 1
       bar(2) = 2
       Foo = bar
    End Function
    
    Private Sub Command1_Click()
       Dim arrayx() As Double       ' note the declaration of a DYNAMIC array
       arrayx = Foo()
       MsgBox arrayx(1)
    End Sub
    

    This code displays a message box with the value "1", just as expected.