Re: VB-101: Passing Arrays ByVal vs ByRef

Tech Tip: Click here to run a free scan for Windows Errors and optimize PC performance



"John Pass" <JohnPass@xxxxxxxxxxxxxxxxxxxxxxxxx> schrieb:
' procedure modifies elements of array and assigns
  ' new reference (note ByVal)
  Sub FirstDouble(ByVal array As Integer())
     Dim i As Integer

     ' double each element value
     For i = 0 To array.GetUpperBound(0)
        array(i) *= 2
     Next

     ' create new reference and assign it to array
     array = New Integer() {11, 12, 13}
  End Sub ' FirstDouble

Since the line where the values of the array 'array' are filled by the
values 11, 12 and 13 is the later part of the same sub-routine where the
earlier changes of values in the same array took place, I would expect these
values to be printed to the screen as output. To me, it looks like the array
values being returned to the calling function were first doubled and that
simply overwritten. Apparently this does not happen.

Arrays are reference types while 'Integer' is not. Consequently an array of integers is a reference type. By passing the array to the method using 'ByVal' the pointer to the array gets copied and the copy is passed to the method. Thus you can change the array's elements, but you cannot change the whole array. In other words, assigning a new array object to the paramater won't change the reference of the variable being passed to the method. You'll have to pass the array 'ByRef' in order to be able to do that.


--
M S Herfried K. Wagner
M V P <URL:http://dotnet.mvps.org/>
V B <URL:http://classicvb.org/petition/>


.



Relevant Pages

  • Re: Updated datestamp doesnt work
    ... Public Sub StoreMyOldVals ... ' store values of current row in array ... Dim dbs As DAO.Database, rst As DAO.Recordset ... Dim var As Variant ...
    (microsoft.public.access.gettingstarted)
  • Re: Updated datestamp doesnt work
    ... Public Sub StoreMyOldVals ... ' store values of current row in array ... Dim dbs As DAO.Database, rst As DAO.Recordset ... Dim var As Variant ...
    (microsoft.public.access.gettingstarted)
  • Re: Updated datestamp doesnt work
    ... Public Sub StoreMyOldVals ... ' store values of current row in array ... Dim dbs As DAO.Database, rst As DAO.Recordset ... Dim var As Variant ...
    (microsoft.public.access.gettingstarted)
  • Re: referencing/sorting arrays
    ... Public Sub SortArrayAscendAs Integer) ... 'Sort an array in ascending order ... Dim Idx01 As Integer ... >> If no data type declaration is made for the argument it becomes a variant. ...
    (microsoft.public.excel.programming)
  • Re: Updated datestamp doesnt work
    ... Public Sub StoreOldVals ... ' store values of current row in array ... Dim n As Integer, intlast As Integer ... Dim var As Variant ...
    (microsoft.public.access.gettingstarted)