Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Changing string variable value within Sub
#2
(02-23-2025, 11:49 PM)dano Wrote: When I run the following program:

Code: (Select All)
a$ = "Hello"
Print "a$ as assigned="; a$
abc a$
Print "a$ AFTER sub="; a$

Print

a$ = "Hello"
Print "a$ as assigned="; a$
abc a$ + " col=10 row=10 height=1 len=50"
Print "a$ AFTER sub="; a$



Sub abc (g$)
    Print "value within the sub="; g$
    g$ = g$ + " world"
End Sub


I get the following output:

a$ as assigned=Hello
value within the sub=Hello
a$ AFTER sub=Hello world

a$ as assigned=Hello
value within the sub=Hello col=10 row=10 height=1 len=50
a$ AFTER sub=Hello


The first instance works as expected - I assign a$, pass it to the sub, alter the value, and upon return it has retained the changed from the Sub.

BUT...why is it that when I pass a$ with a static string, I get all of that value passed to the Sub (Hello col=10 row=10 height=1 len=5), but I cannot retain any changes when we return from the Sub ?  Regardless of what I change g$ to in the sub it always reverts back to Hello.

... because line 10 of your code creates a temporary string build from the current a$ contents and the literal string you add to it, that temporary string is then passed to the sub and not the original a$, i.e. the sub only modifies the temporary string it got passed, but that is discarded as soon as the sub returns and a$ is in fact never touched by the sub.
Reply


Messages In This Thread
RE: Changing string variable value within Sub - by RhoSigma - 02-24-2025, 12:12 AM



Users browsing this thread: 2 Guest(s)