Results 1 to 3 of 3

Thread: ByRef, ByVal?

  1. #1

    Thread Starter
    Addicted Member Dim A's Avatar
    Join Date
    Jul 2000
    Posts
    201
    I understand the concepts of by reference and by value, but has anyone else encountered a problem with passing a variable by reference and then that variable being reset for apparently no reason?

    I called something like this:
    Code:
    subroutine(ByRef oIndex as integer)
    And it would set oIndex to 0 after it completed, but it would always have the proper value all the way through the sub routine. Setting oIndex to ByVal solved the problem no sweat, but I was wondering if anyone knows why this happened. It did it on several subroutines.

    The Routines only used oIndex as an index for a class/struct, and were used very rarely throughout the subroutine.


  2. #2
    Former Admin/Moderator MartinLiss's Avatar
    Join Date
    Sep 1999
    Location
    San Jose, CA
    Posts
    33,431
    I'm not sure what it is you are saying happened, but (and you may know this) when you call a subroutine with a ByRef variable, you are actually calling the subroutine with the address of that variable, so the subroutine has the potential to change the value of the variable. So in the following example the MsgBox will display 55 and not 6.

    Code:
    Private Sub Form_Load()
    
        Dim MyIndex As Integer
        
        MyIndex = 6
        
        subroutine MyIndex
        
        MsgBox MyIndex
        
    End Sub
    
    
    Public Sub subroutine(ByRef oIndex As Integer)
    
        oIndex = 55
    
    End Sub

  3. #3
    transcendental analytic kedaman's Avatar
    Join Date
    Mar 2000
    Location
    0x002F2EA8
    Posts
    7,221
    Have you tried put a break on the last line in your subroutine, if your oIndex is 0 you could probably track the change somewhere, otherways there might be another problem, ie, if youre passing a property of an object or a read only value
    Use
    writing software in C++ is like driving rivets into steel beam with a toothpick.
    writing haskell makes your life easier:
    reverse (p (6*9)) where p x|x==0=""|True=chr (48+z): p y where (y,z)=divMod x 13
    To throw away OOP for low level languages is myopia, to keep OOP is hyperopia. To throw away OOP for a high level language is insight.

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width