CodeGuru Home VC++ / MFC / C++ .NET / C# Visual Basic VB Forums Developer.com
Results 1 to 4 of 4
  1. #1
    Join Date
    Feb 2001
    Posts
    51

    parameter not passed byref

    I ran the following code expecting the form's caption to be set to 10, but instead it was set to 5. Evidently i was passed byval instead of byref.

    private Sub Command1_Click()
    Dim i as Integer
    i = 5
    setToTen (i)
    me.Caption = i
    End Sub

    Sub setToTen(byref n as Integer)
    n = 10
    End Sub




    I'm using Windows 2000 Professional with VB6 (service pack 5). Does the above code pass the parameter by reference on other platforms?



  2. #2
    Join Date
    Feb 2001
    Location
    Arkansas
    Posts
    12

    Re: parameter not passed byref

    The default method in VB is byRef, you don't have to specify byref in the function.

    The reason that you got the result you did is that even though you successfully called the function you didn't return the value to the variable; Here is a very concise code example that will produce the desired results;



    private Sub Command1_Click()
    Dim i as Integer
    i = setToTen
    me.Caption = i
    End Sub

    Function SetToTen()as integer
    SetToTen = 10
    end function





    Hope this helps



  3. #3
    Join Date
    Feb 2001
    Posts
    51

    Re: parameter not passed byref

    There is no need to return a value from a sub when the input is passed ByRef.

    Evidently using parenthesis with a Sub causes the parameter be passed ByVal even when ByRef is explicitly indicated in the Sub's definition.

    The following code correctly passes the input ByRef without using a return value:

    private Sub Command1_Click()
    Dim i as Integer
    setToTen i 'no parenthesis
    me.Caption = i
    End Sub

    Sub SetToTen(n As Integer)
    n = 10
    end function



  4. #4
    Join Date
    Jun 2000
    Location
    Nepal
    Posts
    108

    Re: parameter not passed byref

    You know what happened?

    When you passed as

    SetToTen (i)

    you must have noted that the function name and (i) have a space in between. The correct way of calling a function is either as you did

    SetToTen i

    or

    Call SetToTen(i)

    In this last case, you will note that the (i) and the function name have no space in between.

    In

    SetToTen (i)

    what happened is that VB tried to evaluate the expression (i) and passed the result By Value, not the variable i By Reference as you wanted.


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

Featured