Android Question External variable changes internal value in a Sub after being passed.

SeaBee

Member
Licensed User
I was under the impression that once you pass a variable to a Sub, it will not change inside the Sub, even if the external value in Main changes. The variable is declared as Private in Sub Globals and is passed to the Sub as a parameter. After the Sub is launched, the internal value is changing with the Sub Main value, whereas I want it to be fixed to the value that was passed when the Sub was launched.

Have I got a bidden bug somewhere, or is this expected behaviour?
 

ac9ts

Active Member
Licensed User
Longtime User
Sound like the variable passing is being done by reference rather than by value (which I think is what you want?)
 
Upvote 0

klaus

Expert
Licensed User
Longtime User
How exactly do you transmit the variable.
If you use the same variable name in the Sub as in the Globals routine it's normal, it refers to the global variable.
Can you show us your code?
What exactly do you want to achieve?

@ac9ts Variables are transmitted by value only. Transmission by reference doesn't exist in B4A.
 
Upvote 0

SeaBee

Member
Licensed User
Sorry, gentlemen, was away for the weekend.

The variable was a double, declared as Private in Sub Globals.

B4X:
Sub Globals
'''
Private someDouble as Double
...
End Sub

Sub Main
...
DoStuff(someDouble)
...
End Sub

Sub DoStuff(thisIsDifferentVariableName)
...
'Here, when someDouble changed in Main, due to calling a function in a Sub in Main from this Sub,
'thisIsDifferentVariableName was tracking the new value of someDouble in Main.
...
End Sub

The problem might be linked to the debugger, as I was fiddling with the code and then hitting Restart debugging, but when I disconnected the 'phone and restarted the PC, this worked fine - but the problem just moved further down the code to where I was taking the upper bound of two values from the function Sub into a local variable in the problem Sub, and iterating through the lower bound, increasing it until it matched the old upper bound. This I never got work, as the two values were calculated in the same Main function sub, and the upper bound was increasing with the lower bound each time, so a match was never found - just an infinite loop. Again, this was a locally declared variable (double) equated to the temporary value of the function in Main, which should have remained static after reading it outside the subsequent loop (Do Until...Loop).

In the end I solved the problem by embedding the relevant functions into the DoStuff sub, and it works fine - but doesn't explain why this 'variable tracking' was occurring.
 
Upvote 0
Top