PDA

View Full Version : Problem passing strings to function



EricE
04-06-2024, 15:50
Hello Forum,
Could someone please explain why this program prints "Bacon, Bacon" instead of "Bacon, Tomato"?


'---Load Console Module
Uses "Console"

Dim s(2) as String
Dim sResult as String

function sTest( ByRef s1 as String, ByRef s2 As String) As String
Function = s1 + ", " + s2
End Function

s(1) = "Bacon"
s(2) = "Tomato"

sResult = sTest( s(1), s(2))

printl sResult

WaitKey

If string array elements are not passed to the function, then the correct output "Bacon, Tomato" is produced.


'---Load Console Module
Uses "Console"

Dim t1 As String
Dim t2 as String

Dim sResult as String

function sTest( ByRef s1 as String, ByRef s2 As String) As String
Function = s1 + ", " + s2
End Function

t1 = "Bacon"
t2 = "Tomato"

sResult = sTest( t1, t2 )
printl sResult

'---Wait for a key press
WaitKey

ErosOlmi
05-06-2024, 06:38
Hi Eric,

thanks for reporting this. It is a bug :oops:
I will have a look and fix for the next thinBasic version.

Problem is generated by passing BYREF a string array element.
Parser is not considering the element index but always pointing to the very first element of the array s().

A work around is to define BYVAL the string parameters.
In this case it will work because parser will first create a copy of the string expressions s(1) and s(2) and then pass them to the function parameters.

Another work around is to pass BYREF the full array to the function and use array index inside the function.

Will report when solved.

Ciao
Eros



'---Load Console Module
Uses "Console"

Dim s(2) as String
Dim sResult as String

function sTest_ByRef(byref s1 as String, byref s2 As String) As String
Function = s1 + ", " + s2
End Function

function sTest_ByVal(byval s1 as String, byval s2 As String) As String
Function = s1 + ", " + s2
End Function

function sTest_Array(byref StringArray() As String) As String
Function = StringArray(1) + ", " + StringArray(2)
End Function

s(1) = "Bacon"
s(2) = "Tomato"

sResult = sTest_ByRef( s(1), s(2))
printl "sTest_ByRef ", sResult

sResult = sTest_ByVal( s(1), s(2))
printl "sTest_ByVal ", sResult

sResult = sTest_Array(s)
printl "sTest_Array ", sResult

WaitKey

ErosOlmi
10-06-2024, 12:06
This should be fixed in thinBasic 1.13.0.0 just released.

Ciao
Eros

Kinsonye
19-09-2024, 19:08
Switch to ByVal for the parameters in your function.

etermark
23-09-2024, 15:37
When you use ByRef, it passes a reference to the original variable, so any changes inside the function affect the original variable too. In your first code snippet, you're using the same reference for both elements of the array, which is why you're getting "Bacon, Bacon". If you switch to ByVal or make sure to use different variables for the function, it should print "Bacon, Tomato" as expected.