Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Confusion over passing by reference vs passing by value
#1
Let's say that I have the following code:

Code: (Select All)
Option _Explicit

Dim x As Integer
Dim a As String

Print "Passing a numerical variable by reference:"
x = 1
Test1 x
Print "Value of x after subroutine:"; x

Print

Print "Passing a numerical variable by value:"
x = 1
Test1 (x)
Print "Value of x after subroutine:"; x

Print

Print "Passing a string variable by reference:"
a$ = "String1"
Test2 a$
Print "Value of a$ after subroutine:"; a$

Print

Print "Passing a string variable by value:"
a$ = "String1"
Test2 (a$)
Print "Value of a$ after subroutine:"; a$

End


Sub Test1 (y As Integer)
    y = y + 1
End Sub

Sub Test2 (b As String)
    b$ = b$ + " and string 2"
End Sub


This code has 4 main sections:

Section 1: We set as variable "x" to 1 and pass it to a subroutine by reference to the variable "y". The subroutine adds one to the value of y. As expected, when we come out of the subroutine we find that the original variable "x" is now equal to 2.

Section 2: We set as variable "x" to 1 and pass it to a subroutine by value to the variable "y". The subroutine adds one to the value of y. As expected, when we come out of the subroutine we find that the original variable "x" is unchanged because we passed the variable by value rather than by reference.

But what about strings?

In section 3 and 4, I'm doing the same thing but with a string. I pass it to a subroutine both by reference and by value but in both cases the original string variable is changed.

Is this expected behavior? Is it possible to pass a string variable without affecting the original?

I know that I could work around it by assigning the variable to another variable within the subroutine like this:

Code: (Select All)
Sub Test2 (b As String)
dim c as string
c$=b$   
c$ = c$ + " and string 2"
End Sub


This way, I'm not modifying the original string. I just wanted to make sure I'm not missing something obvious.
Reply


Messages In This Thread
Confusion over passing by reference vs passing by value - by hanness - 06-16-2022, 11:21 PM



Users browsing this thread: 2 Guest(s)