Results 1 to 4 of 4

Thread: By val or By ref

  1. #1

    Thread Starter
    Lively Member
    Join Date
    Jan 2000
    Location
    karachi
    Posts
    90
    Hello,
    Can any one tell me how to use
    both in function and what is the diffrece
    and plz with example
    Bye

  2. #2
    Guest
    Byval makes a duplicate of the value you are passing and drops it into the variable name.

    Byref just invents an address in memory where the value can be found when needed.

    i don't think and code samples would be much help, since they both look very similar.

    Byref is slower but takes less memory, and byval is usually faster but has the drawback of using more memory.

    For example, you probably wouldn't use byval for very large strings, because you would instantly clog up some more memory.

  3. #3
    Monday Morning Lunatic parksie's Avatar
    Join Date
    Mar 2000
    Location
    Mashin' on the motorway
    Posts
    8,169
    If not specified, VB uses ByRef as the default.
    I refuse to tie my hands behind my back and hear somebody say "Bend Over, Boy, Because You Have It Coming To You".
    -- Linus Torvalds

  4. #4
    Frenzied Member
    Join Date
    Mar 2000
    Posts
    1,089
    I think Wossname covered the main differences,

    as a code example say you had this sub

    Code:
    Public Sub Augment(Number As Long)
    
    Number = Number + 1
    
    End Sub
    now try this code

    Code:
    Dim a As Long
    
    a = 4
    
    Call Augment(a)
    
    Msgbox a
    as parksie said
    by default the value is passed byref but add the ByRef Keyword to the augment function anyway and run the code.

    you should get a messagebox with a 5 in it

    now change it to ByVal

    you get a messagebox with a 4 in it

    the reason for this is that if you pass a variable byval you cannot change its value outside the sub because you are not passed the variable itself, you are passed a copy of its value.

    hope that helps

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